Skip to content
AgileLogics

Rust Cheat Sheet

Learn Rust from the basics →

Variables & Types

let x = 5;
Immutable binding (the default)
let mut count = 0;
Mutable binding
const MAX_POINTS: u32 = 100_000;
Constant (type required)
let n: i32 = "42".parse().expect("not a number");
Parse a string into a number
let f = x as f64;
Numeric cast

Control Flow

let kind = if n > 0 { "positive" } else { "other" };
if is an expression
for i in 0..10 { }
Loop over a range (end-exclusive)
let v = loop { break 42; };
loop can return a value
match n { 0 => "zero", 1..=9 => "small", _ => "big" }
Exhaustive pattern match
if let Some(x) = maybe { }
Match a single pattern

Ownership & Borrowing

let s2 = s1;
Move: s1 can no longer be used
let s2 = s1.clone();
Explicit deep copy
fn len(s: &String) -> usize
Borrow immutably
fn push(v: &mut Vec<i32>)
Borrow mutably (only one at a time)
fn first<'a>(a: &'a str, b: &'a str) -> &'a str
Lifetime annotation

Collections & Strings

let mut v = vec![1, 2, 3]; v.push(4);
Growable vector
v.get(10)
Safe index — returns Option<&T>
let mut m = HashMap::new(); *m.entry(k).or_insert(0) += 1;
Count with the entry API
let s = String::from("hi"); let slice: &str = &s;
Owned String vs borrowed &str
v.iter().filter(|x| **x > 1).map(|x| x * 2).collect::<Vec<_>>()
Iterator chain

Structs, Enums & Traits

#[derive(Debug, Clone, PartialEq)] struct Point { x: i32, y: i32 }
Struct with derived traits
impl Point { fn new(x: i32, y: i32) -> Self { Self { x, y } } }
Associated function (constructor)
enum Shape { Circle(f64), Rect { w: f64, h: f64 } }
Enum variants carrying data
trait Area { fn area(&self) -> f64; }
Define a trait
fn total<T: Area>(items: &[T]) -> f64
Generic function with a trait bound

Errors

fn read() -> Result<String, io::Error>
Return a Result
let text = fs::read_to_string(path)?;
Propagate an error with ?
value.unwrap_or(0)
Fallback for an Option
fn main() -> Result<(), Box<dyn Error>>
main that can return errors

Concurrency & Cargo

let h = thread::spawn(move || work()); h.join().unwrap();
Spawn and join a thread
let shared = Arc::new(Mutex::new(0));
Shared mutable state across threads
async fn fetch() -> u32 { } ... fetch().await
Async function (needs a runtime such as Tokio)
cargo new app / cargo run / cargo build --release
Create, run, and build a project
cargo test / cargo fmt / cargo clippy
Test, format, and lint