Rust Cheat Sheet
Rust ownership, borrowing, pattern matching, error handling with Result, and core syntax for memory-safe systems code.
2 PagesAdvancedApr 2, 2026
Basic Syntax
Variables, control flow, and printing.
rust
fn main() { let age = 30; // immutable by default let mut count = 0; // mutable let name = "Ada"; let pi: f64 = 3.14159; if age >= 18 { println!("{} is an adult", name); } for i in 0..5 { println!("Count: {}", i); }}
Ownership & Borrowing
Rust's compile-time memory safety model.
rust
fn main() { let s1 = String::from("hello"); let s2 = s1; // s1 moved into s2, s1 no longer valid // println!("{}", s1); // compile error: value moved let s3 = String::from("world"); let len = calculate_length(&s3); // borrow, not move println!("{} has length {}", s3, len);}fn calculate_length(s: &String) -> usize { s.len()}
Error Handling
Result, Option, and the ? operator.
rust
use std::fs::File;fn read_file(path: &str) -> Result<String, std::io::Error> { let contents = std::fs::read_to_string(path)?; // ? propagates errors Ok(contents)}fn main() { match read_file("data.txt") { Ok(text) => println!("{}", text), Err(e) => println!("Error: {}", e), }}
Core Keywords
Common Rust language keywords and types.
- let/let mut- immutable and mutable variable bindings
- &/&mut- shared and exclusive (mutable) borrows
- match- exhaustive pattern matching on values/enums
- Option<T>- Some(value) or None instead of null
- Result<T, E>- Ok(value) or Err(error) for fallible operations
- impl- implements methods or traits on a type
- trait- defines shared behavior, similar to an interface
- lifetime ('a)- annotation ensuring references remain valid
Traits & Generic Bounds
Define shared behavior and constrain generic types.
rust
trait Shape { fn area(&self) -> f64; fn name(&self) -> &str { "shape" } // default method}struct Circle { r: f64 }impl Shape for Circle { fn area(&self) -> f64 { std::f64::consts::PI * self.r * self.r }}fn print_area<T: Shape>(s: &T) { println!("{}: {}", s.name(), s.area());}// Trait object for dynamic dispatchlet shapes: Vec<Box<dyn Shape>> = vec![Box::new(Circle { r: 2.0 })];
Iterator Adapters
Lazy, composable transformations over collections.
rust
let nums = vec![1, 2, 3, 4, 5, 6];let result: Vec<i32> = nums.iter() .filter(|&&x| x % 2 == 0) .map(|&x| x * 10) .collect();// [20, 40, 60]let sum: i32 = nums.iter().sum();let max = nums.iter().max();let found = nums.iter().find(|&&x| x > 3); // Some(&4)let total: i32 = nums.iter().fold(0, |acc, x| acc + x);
Smart Pointers
Box, Rc, and RefCell for heap allocation and shared ownership.
rust
use std::rc::Rc;use std::cell::RefCell;// Box: single owner, heap allocationlet b = Box::new(5);// Rc: multiple owners, single threadlet a = Rc::new(vec![1, 2, 3]);let b = Rc::clone(&a);println!("count: {}", Rc::strong_count(&a)); // 2// RefCell: interior mutability, checked at runtimelet cell = RefCell::new(10);*cell.borrow_mut() += 5;println!("{}", cell.borrow()); // 15
Cargo Commands
Common cargo workflow commands.
- cargo new- create a new project with a manifest and src layout
- cargo build --release- compile with optimizations into target/release
- cargo run- build and run the current binary crate
- cargo test- run unit, integration, and doc tests
- cargo clippy- lint for common mistakes and idiomatic improvements
- cargo fmt- format source with rustfmt
- cargo add- add a dependency to Cargo.toml (1.62+)
- cargo doc --open- generate and view HTML documentation
Pro Tip
Prefer iterator combinators (.map(), .filter(), .fold()) over manual loops with indices — they're idiomatic, zero-cost, and avoid bounds-check bugs.
Was this cheat sheet helpful?
Explore Topics
#Rust#RustCheatSheet#Programming#Advanced#BasicSyntax#OwnershipBorrowing#ErrorHandling#CoreKeywords#CheatSheet#SkillVeris