FerrousPath

Cheatsheet

The syntax you reach for daily, and what the most common compiler errors are telling you.

Bindings and types

let x = 5;
Immutable binding
let mut x = 5;
Mutable binding
let x: u64 = 5;
With a type annotation
const MAX: u32 = 10;
Compile-time constant
i8 … i128, u8 … u128, isize, usize
Integers
f32, f64, bool, char
Other scalars
(i32, &str) [u8; 4] &[u8]
Tuple, array, slice
x as f64 u8::try_from(x)
Cast; checked conversion

Ownership and borrowing

let b = a;
Moves a (unless the type is Copy)
let b = a.clone();
Explicit deep copy
&a
Shared borrow: many readers
&mut a
Exclusive borrow: one writer
fn f(s: &str)
Borrow in a signature
fn f<'a>(x: &'a str) -> &'a str
Result lives as long as the input
drop(a);
End ownership now

Control flow and patterns

if c { a } else { b }
An expression
loop { break value; }
Loop yielding a value
for x in &v { } for i in 0..n { }
Iteration
match x { 1 | 2 => a, 3..=9 => b, _ => c }
Exhaustive match
if let Some(v) = opt { }
Match one pattern
let Some(v) = opt else { return };
Bind or diverge
while let Some(t) = stack.pop() { }
Loop while matching
Point { x, .. } (a, _) n @ 1..=5 x if x > 0
Destructuring, binding, guards

Option and Result

opt? res?
Propagate None / Err
opt.unwrap_or(d) opt.unwrap_or_default()
Fallbacks
opt.map(f) opt.and_then(f) opt.filter(p)
Transform
opt.ok_or(e) res.ok()
Convert between them
res.map_err(f) res.unwrap_or_else(f)
Handle errors
opt.take() opt.as_ref() opt.as_mut()
Move out / borrow inside
res.expect("why this cannot fail")
Panic with a reason

Structs, enums, traits

struct P { x: f64, y: f64 }
Struct
enum Shape { Circle(f64), Rect { w: f64, h: f64 } }
Enum with data
impl P { fn new() -> Self { … } fn len(&self) -> f64 { … } }
Methods
trait Area { fn area(&self) -> f64; }
Trait
impl Area for P { … }
Implementation
#[derive(Debug, Clone, PartialEq, Eq, Hash, Default)]
Derive common traits
fn f(x: impl Area) fn f<T: Area>(x: T)
Static dispatch
Box<dyn Area> &dyn Area
Dynamic dispatch

Collections and iterators

vec![1, 2, 3] Vec::with_capacity(n)
Vectors
String::from("a") format!("{x}") s.as_str()
Strings
HashMap::new() *m.entry(k).or_insert(0) += 1
Maps and the entry API
v.iter() v.iter_mut() v.into_iter()
&T, &mut T, T
.map(f) .filter(p) .enumerate() .zip(o) .rev() .take(n) .skip(n)
Adapters (lazy)
.collect::<Vec<_>>() .sum() .count() .fold(init, f)
Consumers
.any(p) .all(p) .find(p) .position(p) .max_by_key(f)
Searching
v.sort() v.sort_by_key(f) v.dedup() v.retain(p)
In-place operations

Smart pointers and concurrency

Box<T>
Heap allocation, one owner
Rc<T> Arc<T>
Shared ownership (single / multi-threaded)
Cell<T> RefCell<T>
Interior mutability, one thread
Mutex<T> RwLock<T> AtomicU64
Interior mutability, many threads
Arc<Mutex<T>>
Shared mutable state across threads
thread::spawn(move || …) thread::scope(|s| …)
Threads
mpsc::channel()
Message passing
async fn f() { g().await }
Async; needs an executor

Cargo

cargo new app cargo init
Create a project
cargo check
Type-check fast
cargo run cargo run --release
Build and run
cargo test cargo test name -- --nocapture
Test
cargo fmt cargo clippy
Format and lint
cargo add serde --features derive
Add a dependency
cargo doc --open
Browse documentation
cargo +nightly miri test
Detect undefined behaviour

Reading compiler errors

Run rustc --explain E0382 for the full explanation of any code.

CodeMeaningUsual fix
E0382use of moved valueBorrow instead of moving, clone, or restructure so one owner remains.
E0499two mutable borrows at onceEnd the first borrow before starting the second; split the data; use indices.
E0502mutable borrow while immutably borrowedFinish reading before writing, or copy the value out first.
E0505moved out while borrowedMake sure no reference is used after the move.
E0506assigned to while borrowedSame remedy as E0502.
E0597borrowed value does not live long enoughMove the owner to an outer scope, or return an owned value.
E0106missing lifetime specifierSay which input the returned reference borrows from, or return an owned value.
E0277trait bound not satisfiedAdd the bound to your generic, implement or derive the trait, or convert the type.
E0308mismatched typesCheck for a stray semicolon, a missing conversion, or branches of different types.
E0282type annotations neededAnnotate the binding or use the turbofish: parse::<i32>().
E0004non-exhaustive patternsHandle the listed cases.
E0373closure may outlive borrowed valueAdd move to the closure.