Rust

Basics

let x = 5;Immutable variable
let mut x = 5;Mutable variable
const MAX: u32 = 100;Compile-time constant
fn main() { }Entry point
println!("Hello {}", name)Print with format
println!("{:?}", val)Debug print
let x: i32 = 5;Explicit type annotation
use std::io;Import module

Data Types

i8/i16/i32/i64/i128Signed integers
u8/u16/u32/u64/u128Unsigned integers
f32 / f64Floating point
booltrue or false
charUnicode character
&strString slice (borrowed)
StringOwned string
(i32, f64)Tuple
[i32; 5]Fixed-size array
Vec<T>Dynamic array
Option<T>Some(T) or None
Result<T, E>Ok(T) or Err(E)

Ownership & Borrowing

let s2 = s1;Move ownership (s1 invalid)
let s2 = s1.clone();Deep copy (both valid)
&xImmutable borrow (reference)
&mut xMutable borrow
fn f(s: &String)Borrow in function
fn f(s: &mut String)Mutable borrow in fn
'a lifetime annotationExplicit lifetime
'staticLives entire program

Structs & Enums

struct Point { x: f64, y: f64 }Named struct
impl Point { fn new() -> Self }Implement methods
self / &self / &mut selfMethod receivers
enum Color { Red, Green, Blue }Simple enum
enum Msg { Quit, Move {x,y} }Enum with data
match val { Pat => expr }Pattern matching
if let Some(x) = opt { }Conditional unwrap
#[derive(Debug, Clone)]Auto-derive traits

Error Handling

Result<T, E>Recoverable error type
Ok(val) / Err(e)Result variants
.unwrap()Panic if Err/None
.expect("msg")Panic with message
?Propagate error (return Err)
.unwrap_or(default)Default on error
.map_err(|e| ...)Transform error
panic!("msg")Unrecoverable error

Traits

trait MyTrait { fn method(); }Define trait
impl Trait for Type { }Implement trait
fn f(x: &dyn Trait)Dynamic dispatch
fn f(x: impl Trait)Static dispatch
fn f<T: Trait>(x: T)Generic with bound
where T: Trait + CloneWhere clause bounds
Box<dyn Trait>Trait object on heap

Collections

Vec::new() / vec![1,2,3]Create vector
v.push(x) / v.pop()Add / remove last
v.iter().map(|x| ...)Iterator map
v.iter().filter(|x| ...)Iterator filter
.collect::<Vec<_>>()Collect into container
HashMap::new()Create hash map
map.insert(k, v)Insert key-value
map.get(&k)Get value (returns Option)
HashSet::new()Create hash set
.for_each(|x| ...)Iterate with closure

Control Flow

if cond { } else { }If expression
let x = if c { a } else { b };If as expression
loop { break val; }Infinite loop with return
while cond { }While loop
for x in iter { }For-in loop
for i in 0..10 { }Range loop
match val { _ => {} }Match (exhaustive)
allprintabledoc.com