Cheatsheet
A one-screen reference for Rust idioms: ownership, borrowing, lifetimes, error handling, common collection ops, async, and the toolchain. Bookmark it.
Rust in one page
EXAMPLE
// ===== Vars + mutability =====
let x = 1; // immutable
let mut y = 2; y += 1;
const PI: f64 = 3.14;
// ===== Ownership + borrowing =====
let s = String::from("hi");
let r1 = &s; // shared borrow (multiple ok)
let s2 = &s; let s3 = &s;
// let m = &mut s; // would conflict; mutable borrows are exclusive
let mut t = String::from("world");
let rm = &mut t; // exclusive borrow
rm.push_str("!");
// Move vs copy
let v = vec![1,2,3]; let v2 = v; // moved; v is invalid here
let n = 5; let n2 = n; // copied (i32 is Copy)
// ===== Strings =====
let s: String = String::from("hi");
let slice: &str = &s[0..2];
let owned: String = slice.to_owned();
let cat = format!("{} {}", "hello", s);
// ===== Vec, HashMap, HashSet =====
use std::collections::{HashMap, HashSet};
let mut xs: Vec<i32> = vec![1, 2, 3];
xs.push(4);
let sum: i32 = xs.iter().sum();
let evens: Vec<_> = xs.iter().copied().filter(|n| n % 2 == 0).collect();
let mut m = HashMap::new();
m.insert("a", 1);
*m.entry("a").or_insert(0) += 1;
let s: HashSet<_> = [1, 2, 3].iter().copied().collect();
// ===== Pattern matching =====
match xs.first() {
Some(0) => println!("zero"),
Some(n) if *n > 0 => println!("positive {n}"),
Some(_) => println!("negative"),
None => println!("empty"),
}
if let Some(first) = xs.first() { println!("{first}") }
// ===== Structs + enums + traits =====
struct Order { id: String, total_cents: u64 }
impl Order {
fn new(id: &str, t: u64) -> Self { Self { id: id.into(), total_cents: t } }
fn total_aud(&self) -> f64 { self.total_cents as f64 / 100.0 }
}
enum Status { New, Paid, Shipped, Cancelled }
trait Greet { fn greet(&self) -> String; }
impl Greet for Order { fn greet(&self) -> String { format!("order {}", self.id) } }
// ===== Error handling with Result =====
use std::fs;
fn read(path: &str) -> Result<String, std::io::Error> { fs::read_to_string(path) }
let body = read("x.txt")?; // ? propagates the error
// anyhow / thiserror for ergonomic apps + libraries (see rust/errors lesson)
// ===== Lifetimes — usually inferred, sometimes explicit =====
fn first_word<>(s: & str) -> & str {
s.split_whitespace().next().unwrap_or("")
}
// ===== Iterators (lazy, zero-cost) =====
let sum: i32 = (1..=100).filter(|n| n % 2 == 0).sum();
let pairs: Vec<_> = xs.iter().zip(["a","b","c"]).collect();
let max = xs.iter().max(); // Option<&i32>
// ===== Async (with Tokio) =====
// #[tokio::main]
// async fn main() -> anyhow::Result<()> {
// let body = reqwest::get("https://example.com").await?.text().await?;
// println!("{}", body.len());
// Ok(())
// }
// ===== Smart pointers =====
use std::rc::Rc;
use std::sync::Arc;
let shared = Rc::new(1); // single-threaded shared owner
let asynced = Arc::new(2); // multi-threaded shared owner
use std::cell::RefCell;
let cell = RefCell::new(0);
*cell.borrow_mut() += 1;
// ===== Cargo + tooling =====
// cargo new myapp
// cargo run
// cargo test
// cargo bench --features=nightly
// cargo fmt; cargo clippy -- -D warnings
// cargo build --release
// ===== Pitfalls =====
// - Cloning to "appease the borrow checker" works but is slow if you do it in a loop
// - .unwrap() in production code => panic; use ? or match
// - Async + sync I/O mix → use tokio::task::spawn_blocking for sync work
// - String vs &str confusion — owned vs borrowed; pick based on lifetime needs
// - Lifetimes annotations: try writing without first; add only when compiler asks
Why it matters
Run `cargo clippy -- -D warnings` in CI from day one. The lints catch real bugs (unused results, redundant clones, suspicious match arms) and they grow with the language — letting them fail the build keeps the codebase modern and idiomatic without a team-wide style decree.
Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.
Discussion
Loading…