Rust cheatsheet – syntax overview
76 key commands and patterns for quick reference.
Basics Types Control flow Functions & closures Ownership & Borrowing Structs, enums & patterns Option & Result Collections & iterators Traits & Generics Cargo & tests Smart pointers & threads
Basics
println!("{} {x} {:?}", a, v); | Output: Display, variable in the text, Debug |
let x = 5; | Immutable variable |
let mut y = 5; | Mutable variable |
const MAX: u32 = 100; | Constant (type required) |
let x = x * 2; | Shadowing: rebind a name |
x as f64 | Explicit type conversion for numbers |
"42".parse::<i32>() | Convert text to a number (returns a Result) |
Types
i32 u8 i64 usize f64 | Number types (u = unsigned, usize for indices) |
bool char | Boolean and Unicode character (4 bytes) |
&str String | Text view (borrowed) and owned text |
(i32, &str) | Tuple: t.0, t.1 |
[i32; 3] | Fixed-length array |
Vec<i32> &[i32] | Growable list and slice view |
Option<T> Result<T, E> | Possibly no value / success or error |
Control flow
if a > b { } else if a == b { } else { } | Branching (can also be used as an expression) |
for i in 0..5 { } | Loop over 0..4 |
for i in 1..=5 { } | Loop over 1..5 (end inclusive) |
while bedingung { } | Loop with a condition |
loop { break wert; } | Infinite loop that yields a value via break |
'aussen: for ... { break 'aussen; } | Loop label for nested loops |
match x { 1 => "a", 2..=5 => "b", _ => "c" } | Pattern matching (must be exhaustive) |
Functions & closures
fn f(a: i32, b: i32) -> i32 { a + b } | Function; the last expression without ; is the return value |
return x; | Return early from the function |
|x| x + 1 | Closure (anonymous function) |
move |x| x + n | Closure that owns the captured values |
fn f(g: impl Fn(i32) -> i32) | Closure or function as a parameter |
fn f() -> impl Fn(i32) -> i32 | Return a closure |
Ownership & Borrowing
let b = a; | Move (for String/Vec) or copy (for numbers) |
let b = a.clone(); | Explicit deep copy |
&x | Immutable reference (any number) |
&mut x | Mutable reference (only one at a time) |
*r | Dereference: the value behind a reference |
&s[0..3] | Slice: a portion without copying |
fn f<'a>(x: &'a str) -> &'a str | Lifetime annotation |
Structs, enums & patterns
struct P { x: i32, y: i32 } | Struct with named fields |
impl P { fn neu() -> Self { ... } } | Methods and associated functions |
#[derive(Debug, Clone, PartialEq)] | Implement traits automatically |
enum E { A, B(i32), C { x: i32 } } | Enum with data in its variants |
if let Some(x) = opt { } | Match only one case |
let Some(x) = opt else { return; }; | let-else: bail out early (since 1.65) |
Punkt { x, .. } | Destructuring, ignoring the rest |
Option & Result
opt.unwrap_or(0) | Value or default |
opt.map(|x| x + 1) | Transform the content if present |
opt.ok_or("missing")? | Convert an Option to a Result and propagate it |
res? | Return early on Err, unwrap on Ok |
res.map_err(|e| e.to_string()) | Convert the error type |
res.unwrap() res.expect("Text") | Unwrap, panic on error (only for tests/prototypes) |
fn main() -> Result<(), Box<dyn Error>> | main may return errors |
Collections & iterators
let mut v = vec![1, 2, 3]; v.push(4); | Create and extend a Vec |
v.len() v.is_empty() v.get(i) | Length, empty?, safe access (Option) |
v.iter().map(|x| x * 2).collect::<Vec<_>>() | Transform and collect |
v.iter().filter(|x| **x > 1) | Filter (the closure receives &&T) |
v.iter().sum::<i32>() | Sum (also product, min, max, count) |
for (i, x) in v.iter().enumerate() | Index and value |
m.entry(k).or_insert(0) | HashMap: get or create an entry |
s.split_whitespace().collect::<Vec<_>>() | Split text into words |
Traits & Generics
trait T { fn f(&self); } | Define a trait |
impl T for Typ { fn f(&self) { } } | Implement a trait |
fn f<T: Display + Clone>(x: T) | Generic function with trait bounds |
fn f<T>(x: T) where T: Display | Bounds in a where clause |
Box<dyn T> &dyn T | Trait objects (dynamic dispatch) |
impl Iterator for X { type Item = u32; fn next(&mut self) -> Option<u32> } | Build your own iterator |
Cargo & tests
cargo new name | Create a new project |
cargo run cargo run --release | Build and run (debug / optimized) |
cargo check cargo build | Check only / compile |
cargo add crate_name | Add a dependency |
cargo test | Run tests |
cargo fmt cargo clippy | Format and lint |
#[test] fn name() { assert_eq!(a, b); } | Test function |
Smart pointers & threads
Box::new(x) | Put a value on the heap |
Rc::new(x) Rc::clone(&a) | Shared ownership (one thread) |
RefCell::new(x) .borrow_mut() | Interior mutability (runtime check) |
Arc::new(Mutex::new(x)) | Shared mutable state across threads |
thread::spawn(move || { ... }) | Start a thread |
handle.join().unwrap() | Wait for a thread and get its result |
let (tx, rx) = mpsc::channel(); | Channel for messages between threads |