Rust Cheat Sheet

Essential Rust syntax and concepts. Ownership, borrowing, lifetimes, pattern matching, traits, enums, error handling, and common standard library types.

Variables & Types Ownership & Borrowing Structs & Enums Pattern Matching Traits & Generics Error Handling Collections & Iterators Common Macros

Variables & Types

let x = 5; Immutable binding (default)
let mut x = 5; Mutable binding
const MAX: u32 = 100; Compile-time constant
let x = 5; let x = x + 1; Shadowing (re-declare same name)
i8, i16, i32, i64, i128, isize Signed integer types
u8, u16, u32, u64, u128, usize Unsigned integer types
f32, f64 Floating point types
bool, char Boolean and Unicode char
&str String slice (borrowed, immutable)
String Owned, growable string
(i32, f64, bool) Tuple type
[i32; 5] Array with fixed length

Ownership & Borrowing

let s2 = s1; Move ownership (s1 invalid after)
let s2 = s1.clone(); Deep copy (both valid)
fn read(s: &String) Immutable borrow (shared reference)
fn modify(s: &mut String) Mutable borrow (exclusive reference)
&T Shared reference (many readers)
&mut T Exclusive reference (one writer)
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str Lifetime annotation
'static Lifetime for entire program duration
#[derive(Copy, Clone)] Implement Copy trait (stack-only types)

Structs & Enums

struct Point { x: f64, y: f64 } Named-field struct
struct Color(u8, u8, u8); Tuple struct
impl Point { fn new(x: f64, y: f64) -> Self { ... } } Implementation block
impl Point { fn distance(&self) -> f64 { ... } } Method with &self
enum Direction { Up, Down, Left, Right } Simple enum
enum Option { Some(T), None } Generic enum (from std)
enum Result { Ok(T), Err(E) } Result enum (from std)
Option::Some(42).unwrap() Extract value (panics if None)

Pattern Matching

match value { 1 => "one", 2 => "two", _ => "other" } Match expression
match opt { Some(x) => x, None => 0 } Match on Option
if let Some(x) = opt { ... } If-let (single pattern)
while let Some(x) = iter.next() { ... } While-let loop
let (x, y, z) = (1, 2, 3); Tuple destructuring
let Point { x, y } = point; Struct destructuring
match x { 1..=5 => "low", 6..=10 => "high", _ => "?" } Range pattern
match x { n if n < 0 => "neg", _ => "pos" } Match guard

Traits & Generics

trait Summary { fn summarize(&self) -> String; } Define trait
impl Summary for Article { fn summarize(&self) -> String { ... } } Implement trait
fn notify(item: &impl Summary) Trait bound (impl syntax)
fn notify(item: &T) Trait bound (generic syntax)
fn process(item: T) Multiple trait bounds
fn process(item: T) where T: Display + Clone Where clause
#[derive(Debug, Clone, PartialEq)] Auto-derive common traits
Box Trait object (dynamic dispatch)

Error Handling

let f = File::open("file.txt")?; ? operator (propagate error)
result.unwrap() Unwrap or panic
result.expect("failed to open") Unwrap with message
result.unwrap_or(default) Unwrap or use default
result.map(|v| v + 1) Transform Ok value
result.and_then(|v| another_op(v)) Chain fallible operations
impl From for MyError Custom error conversion
Err(anyhow!("something failed")) anyhow crate (dynamic errors)

Collections & Iterators

let v: Vec = Vec::new(); Empty vector
let v = vec![1, 2, 3]; Vector macro
v.push(4); v.pop(); Add/remove last element
let mut map = HashMap::new(); Empty hash map
map.insert("key", "value"); Insert into map
map.get("key") Get value (returns Option)
v.iter().filter(|x| **x > 2).collect::>() Iterator chain
v.iter().map(|x| x * 2).sum::() Map and sum
(0..10).for_each(|i| println!("{}", i)) Range iterator

Common Macros

println!("Hello, {}!", name) Print with newline
format!("x = {x}") Format string
vec![1, 2, 3] Create Vec
todo!() Mark unfinished code (panics)
unimplemented!() Mark unimplemented (panics)
assert_eq!(a, b) Assert equality (test)
dbg!(&value) Debug print with file:line
#[cfg(test)] mod tests { ... } Test module
#[test] fn it_works() { assert!(true); } Test function

More Cheat Sheets