Short answer: Create a project with cargo new app, run it with cargo run and ship cargo build --release. Variables are immutable unless marked mut; each value has one owner, and you lend it with & (shared) or &mut (exclusive). Model states with enum and match, return Result<T, E> from anything that can fail and propagate errors with ?. Use Vec, HashMap and iterator chains such as .iter().map().filter().collect().
The examples in this Rust cheat sheet were run with Rust 1.99.0 and Cargo 1.99.0 (edition 2024) on Linux on 9 October 2026, and checked with cargo clippy.
Table of Contents
rustup and cargo commands
Command
What it does
rustup update stable
Install or update the stable toolchain
cargo new app / cargo new --lib mylib
New binary or library project (edition 2024 by default)
cargo run -- --verbose
Build and run; arguments after -- go to your program
cargo build --release
Optimised binary in target/release/
cargo check
Type-check without producing a binary (fast)
cargo test
Run unit, integration and doc tests
cargo clippy
Lints for common mistakes
cargo fmt
Format the code with rustfmt
cargo add serde --features derive
Add a dependency to Cargo.toml
cargo update
Update Cargo.lock within allowed versions
cargo doc --open
Build and open documentation for your crate and dependencies
rustup target add x86_64-unknown-linux-musl
Add a target for static Linux binaries (cargo build --target ...)
v.iter().map(|n| n * n).filter(|n| *n > 1).collect::<Vec<_>>()
Lazy iterator chain, collected into a new Vec
v.iter().sum::<i32>(), .count(), .max()
Common consumers
for (i, x) in v.iter().enumerate()
Index and value
HashMap::new() + m.insert(k, v) + m.get(&k)
Hash map from std::collections
*m.entry(k).or_insert(0) += 1;
Counting with the entry API
Error handling with Result and ?
use std::{error::Error, fs};
fn parse_port(s: &str) -> Result<u16, std::num::ParseIntError> {
let p: u16 = s.trim().parse()?; // ? returns the error early
Ok(p)
}
fn run() -> Result<(), Box<dyn Error>> {
let text = fs::read_to_string("/etc/hostname")?;
println!("{}", text.trim());
Ok(())
}
fn main() {
if let Err(e) = run() {
eprintln!("error: {e}");
std::process::exit(1);
}
}
Syntax
Use it for
Result<T, E>: Ok(v) / Err(e)
Any operation that can fail
?
Return the error to the caller, converting it with From if needed
Box<dyn Error>
Any error type; fine for binaries and scripts
Custom enum + impl Display + impl Error
Typed errors for libraries
.unwrap() / .expect("msg")
Panic on error; acceptable in tests and prototypes
.ok_or(err)
Turn an Option into a Result
panic!("...")
Unrecoverable bug; unwinds the thread
Traits, generics and threads
trait Check {
fn name(&self) -> String;
fn healthy(&self) -> bool { true } // default method
}
impl Check for Server {
fn name(&self) -> String { format!("{}:{}", self.name, self.port) }
}
fn report(c: &impl Check) -> String { /* static dispatch */ c.name() }
fn largest<T: PartialOrd + Copy>(items: &[T]) -> T { // trait bounds
items.iter().copied().fold(items[0], |m, x| if x > m { x } else { m })
}
let checks: Vec<Box<dyn Check>> = vec![Box::new(srv)]; // dynamic dispatch
Syntax
What it does
thread::spawn(move || { ... })
New OS thread; move transfers captured values
handle.join().unwrap()
Wait for a thread
thread::scope(|s| { s.spawn(|| ...); })
Threads that may borrow local data
Arc::new(Mutex::new(0))
Shared, mutable state across threads
*c.lock().unwrap() += 1;
Lock, modify, unlock at end of statement
let (tx, rx) = mpsc::channel();
Message passing between threads
The standard library has no async runtime. For async network services, most projects add a runtime crate such as Tokio with cargo add.
Files, arguments and a log example
For server admins: count failed SSH logins per source IP, reading the log line by line so large files stay cheap.
use std::collections::HashMap;
use std::env;
use std::fs::File;
use std::io::{self, BufRead, BufReader};
fn main() -> io::Result<()> {
let path = env::args().nth(1).unwrap_or_else(|| "/var/log/secure".into());
let reader = BufReader::new(File::open(&path)?);
let mut hits: HashMap<String, u32> = HashMap::new();
for line in reader.lines() {
let line = line?;
if let Some(rest) = line.split("Failed password").nth(1)
&& let Some(ip) = rest.split(" from ").nth(1)
{
let ip = ip.split_whitespace().next().unwrap_or("?");
*hits.entry(ip.to_string()).or_insert(0) += 1;
}
}
let mut top: Vec<_> = hits.into_iter().collect();
top.sort_by_key(|(_, n)| std::cmp::Reverse(*n));
for (ip, n) in top.iter().take(10) {
println!("{n:>7} {ip}");
}
Ok(())
}
In short: A compact reference for current stable Rust covering Cargo, ownership, pattern matching, collections, error handling, traits and threads.Rust Cheat Sheet: what this guide covers.
Necessary cookies enable essential site features like secure log-ins and consent preference adjustments. They do not store personal data.
None
Functional cookies support features like content sharing on social media, collecting feedback, and enabling third-party tools.
None
Analytical cookies track visitor interactions, providing insights on metrics like visitor count, bounce rate, and traffic sources.
None
Advertisement cookies deliver personalized ads based on your previous visits and analyze the effectiveness of ad campaigns.
None
Unclassified cookies are cookies that we are in the process of classifying, together with the providers of individual cookies.
None
Try:
Free checklist
cPanel and DirectAdmin server hardening checklist
A two-page PDF of the checks we run on every hosting server: SSH, firewall, PHP, mail, backups and updates. Get it with the srvScripts newsletter (about twice a month, one-click unsubscribe).
We send a confirmation link first; the download appears after you confirm. Privacy policy.
srvScripts GenieFinds the right tool, guide or fix
Tell me what is wrong, for example emails going to spam, SSL expired on example.com or 550 5.7.1 rejected. Add a domain or IP address and I run a quick check right here, for example check DNS for example.com.
Never paste passwords or keys. Unanswered questions are kept for up to 90 days to improve our guides, with keys, passwords, IP and e-mail addresses masked (best effort: leave out confidential details), and without your IP address, account or cookies. Details