Course Rust
Rust Cheatsheet
A quick, printable reference with essential Rust syntax: mutability, primitive types, pattern matching, Option/Result, ownership, borrowing, structs, collections, and error propagation. Print to PDF with Ctrl/Cmd + P.
Save or print this cheatsheet as PDF
Print-ready layout: open in one click and save as PDF from your browser, no account or email required.
0. Core Rust Invariants & Pitfalls to Avoid
Five borrow-checker and memory-safety rules to keep top of mind.
- Every value has a single owner: passing non-Copy types by value moves ownership and invalidates the source variable.
- Borrowing invariant: you may have many shared immutable borrows (&T) OR one exclusive mutable borrow (&mut T), never both simultaneously.
- Keep String (heap-owned, growable UTF-8) distinct from &str (immutable borrowed string slice).
- Avoid .unwrap() and .expect() in production paths: propagate failures cleanly with ?, match, or unwrap_or.
- Direct indexing slice[i] panics out-of-bounds: use slice.get(i) whenever an index is unvalidated.
1. Variables & Mutability
Declarations & Shadowing
let x = 5; // Immutable by default let mut y = 10; // Mutable (mut) const MAX: u32 = 100; // Constant (explicit type required) let x = x + 1; // Shadowing (binds a new variable)Bindings are immutable by default to make state mutations explicit.
Pitfall: Shadowing (let x = ...) creates a fresh variable and can even change its type, whereas mut mutates the same binding.
2. Primitive Types
Tuples & Arrays
// Tuple (fixed size, heterogeneous types) let tuple: (i32, f64, char) = (500, 6.4, 'z'); let first = tuple.0; // Dot-index access // Array (fixed size, stack allocated, homogeneous types) let array = [1, 2, 3, 4, 5]; let second = array[1];Array bounds are checked at runtime, panicking safely instead of reading corrupt memory.
Pitfall: Byte indexing s[0] on a UTF-8 String does not compile: iterate with .chars() or slice cleanly.
3. Control Flow
Conditionals & if Expressions
// Classic if/else if number < 5 { println!("Small"); } else { println!("Big"); } // if as an expression let condition = true; let number = if condition { 5 } else { 6 };Nearly every block in Rust evaluates as an expression returning its final semicolon-free line.
Pitfall: When using if as an expression, both branches must evaluate to the exact same type.
Loops (loop, while, for)
// loop (infinite until break; can return a value) let res = loop { break 42; }; // conditional while while number != 0 { number -= 1; } // for over a range (1..4 excludes 4; 1..=4 includes 4) for n in 1..4 { println!("{}", n); }Prefer for over ranges or iterators instead of manual index counters.
Pitfall: Adding a trailing semicolon ; turns a block’s return expression into unit () and fails to compile.
4. Pattern Matching & Errors
match, Option & Result
match number { 1 => println!("One"), 2 => println!("Two"), _ => println!("Other"), // Must be exhaustive } match x { Some(val) => println!("Found: {}", val), None => println!("No value"), } match res { Ok(val) => println!("Success: {}", val), Err(e) => println!("Error: {}", e), }The compiler enforces exhaustive pattern matching on every enum variant.
Pitfall: Overusing catch-all _ silences future compiler warnings when new enum variants are added later.
? Error Propagation
use std::fs; use std::io; fn read_username(path: &str) -> Result<String, io::Error> { let contents = fs::read_to_string(path)?; Ok(contents.trim().to_string()) }The ? operator returns Err early or unwraps Ok cleanly.
Pitfall: ? only works inside functions returning a compatible Result or Option (not inside plain fn main()).
5. Ownership & Borrowing
Move & References (& / &mut)
let s1 = String::from("hello"); let s2 = s1; // Ownership is moved (s1 is invalidated!) let len = calculate_length(&s2); // Immutable borrow (&) let mut s3 = String::from("hello"); change(&mut s3); // Exclusive mutable borrow (&mut)At any point you can hold multiple &T references OR one &mut T reference.
Pitfall: Trying to mutate while an active immutable reference is still used later causes a borrow-checker error.
6. Structs, Methods & Collections
Definition & impl
struct Rectangle { width: u32, height: u32, } impl Rectangle { fn area(&self) -> u32 { self.width * self.height } fn square(size: u32) -> Self { Self { width: size, height: size } } } let rect = Rectangle::square(10); let a = rect.area();&self borrows the instance without moving ownership; Self names associated constructors.
Pitfall: Writing fn consume(self) without & transfers ownership into the method and drops the struct on return.
Vec<T> & Iterators
let mut nums = vec![1, 2, 3]; nums.push(4); let doubled: Vec<i32> = nums.iter().map(|n| n * 2).collect(); let first: Option<&i32> = nums.first();Iterators are lazy and compile down to zero-overhead loops when consumed by .collect().
Pitfall: Supply a target type annotation (Vec<i32> or Vec<_>) whenever .collect() cannot infer the collection type.
7. Closures & Zero-Cost Iterators
Closure Traits (Fn, FnMut, FnOnce)
let factor = 3; let scale = |n: i32| n * factor; // Fn: immutable borrow let mut hits = 0; let mut count = || { hits += 1; hits }; // FnMut: mutable borrow let text = String::from("rust"); let consume = move || text.len(); // move: takes ownershipThe compiler automatically infers Fn, FnMut, or FnOnce from how captured variables are used.
Pitfall: Closures that mutate captured state require `mut` on the binding and keep an exclusive borrow active.
Lazy Adapters & Consumers
let nums = [1, 2, 3, 4, 5, 6]; let even_sum: i32 = nums.iter() .copied() .filter(|&n| n % 2 == 0) .map(|n| n * n) .sum();Chaining .filter(), .map(), and .fold() allocates no intermediate vectors.
Pitfall: Forgetting a terminal consumer (.collect(), .sum(), or for) does zero work because adapters are lazy.
8. Modules, Cargo & Automated Testing
Modules & Visibility (pub / pub(crate))
pub mod math { pub fn clamp(val: i32, max: i32) -> i32 { if val > max { max } else { val } } pub(crate) fn helper() -> i32 { 1 } } use crate::math::clamp;Everything in Rust is private by default: export only intentional public items with `pub`.
Pitfall: Making a struct `pub` keeps its fields private unless each exposed field is also marked `pub`.
Unit Tests with #[cfg(test)]
#[cfg(test)] mod tests { use super::*; #[test] fn parses_valid_port() { assert_eq!(8080, "8080".parse::<u16>().unwrap()); } }`#[cfg(test)]` strips unit test modules completely from release builds (`cargo build --release`).
Pitfall: Without `use super::*;`, nested test modules cannot reference private helpers from the parent file.
9. Standard Traits, Box<dyn> & Lifetimes
Dynamic Dispatch & From Conversions
trait Renderer { fn render(&self) -> String; } let widgets: Vec<Box<dyn Renderer>> = Vec::new(); impl From<i32> for Wrapper { fn from(v: i32) -> Self { Self(v) } }Prefer static generics `<T: Trait>` unless heterogeneous collections require `Box<dyn Trait>`.
Pitfall: Traits with generic methods or by-value `Self` return types are not dyn-compatible.
Explicit Function Lifetimes
fn first_word<'a>(line: &'a str) -> &'a str { line.split_whitespace().next().unwrap_or("") }Lifetime parameters link output borrow validity to input parameters without extending actual lifetime.
Pitfall: Returning a reference to a local String created inside a function always fails (dangling reference).
10. Fearless Concurrency (Send, Sync, mpsc, Arc<Mutex>)
Threads & mpsc Channels
use std::sync::mpsc; use std::thread; let (tx, rx) = mpsc::channel(); let handle = thread::spawn(move || { tx.send(42).unwrap(); }); handle.join().unwrap(); let received = rx.recv().unwrap();`move` transfers captured ownership safely into the newly spawned OS thread.
Pitfall: Iterating `for msg in rx` deadlocks forever unless all cloned `tx` senders are eventually dropped.
Shared Mutable State with Arc<Mutex<T>>
use std::sync::{Arc, Mutex}; let shared = Arc::new(Mutex::new(0)); let clone = Arc::clone(&shared); *clone.lock().unwrap() += 1;`Arc<T>` gives atomic multi-thread ownership; `Mutex<T>` enforces exclusive access via RAII guards.
Pitfall: `Rc<T>` and `RefCell<T>` are intentionally not `Send`/`Sync` and fail to compile across threads.