A quick reference for Rust syntax and concepts. Covers ownership and borrowing, lifetimes, traits, enums and pattern matching, Result/Option, structs, iterators, and common macros.
Ownership & Borrowing
| Concept | Syntax | Description |
|---|---|---|
| Ownership | let s = String::from("hi") | Variable owns the value |
| Move | let s2 = s | s is moved to s2, s is invalid |
| Clone | let s2 = s.clone() | Deep copy, both valid |
| Immutable borrow | let r = &s | Read-only reference (multiple allowed) |
| Mutable borrow | let r = &mut s | Read-write reference (exclusive) |
| Borrow rule | &T or &mut T, not both | Cannot mix shared and mutable refs |
| Copy types | i32, f64, bool, char, .. | Stack types are copied, not moved |
Lifetimes
| Syntax | Description |
|---|---|
| fn f<'a>(x: &'a str) -> &'a str | Explicit lifetime annotation |
| struct S<'a> { r: &'a str } | Lifetime in struct (holds reference) |
| impl<'a> S<'a> { } | Lifetime in impl block |
| fn f(x: &str) -> &str | Lifetime elision (compiler infers) |
| 'static | Lives for entire program duration |
| fn f<'a, 'b>(x: &'a str, y: &'b str) | Multiple lifetime parameters |
| where 'a: 'b | Lifetime bound ('a outlives 'b) |
Traits
| Syntax | Description |
|---|---|
| trait Summary { fn summarize(&self) -> String; } | Define a trait |
| impl Summary for Article { .. } | Implement trait for type |
| fn f(x: &impl Summary) | Trait bound (impl syntax) |
| fn f<T: Summary>(x: &T) | Trait bound (generic syntax) |
| fn f<T: Clone + Debug>(x: &T) | Multiple trait bounds |
| fn f(x: &dyn Summary) | Trait object (dynamic dispatch) |
| #[derive(Debug, Clone, PartialEq)] | Auto-derive common traits |
| trait A: B { } | Supertrait (A requires B) |
Enums & Pattern Matching
| Syntax | Description |
|---|---|
| enum Color { Red, Green, Blue } | Simple enum |
| enum Shape { Circle(f64), Rect(f64, f64) } | Enum with data |
| match x { 1 => "one", _ => "other" } | Match expression (exhaustive) |
| match shape { Circle(r) => .. } | Destructure enum variant |
| if let Some(v) = opt { .. } | Match single pattern |
| while let Some(v) = iter.next() { .. } | Loop on pattern match |
| matches!(x, Pattern) | Boolean pattern check macro |
| match (a, b) { (1, 2) => .. } | Match on tuples |
Result & Option
| Pattern | Description |
|---|---|
| Ok(value) / Err(err) | Result variants |
| Some(value) / None | Option variants |
| result? | Propagate error (early return Err) |
| opt.unwrap() | Get value or panic if None/Err |
| opt.unwrap_or(default) | Get value or use default |
| opt.unwrap_or_else(|| compute()) | Get value or compute default |
| result.map(|v| transform(v)) | Transform Ok/Some value |
| result.and_then(|v| maybe_fail(v)) | Chain fallible operations |
| opt.is_some() / opt.is_none() | Check variant without consuming |
Structs
| Syntax | Description |
|---|---|
| struct Point { x: f64, y: f64 } | Named-field struct |
| struct Color(u8, u8, u8) | Tuple struct |
| struct Unit; | Unit struct (no fields) |
| let p = Point { x: 1.0, y: 2.0 } | Create struct instance |
| let p2 = Point { x: 3.0, ..p } | Struct update syntax |
| impl Point { fn new(x: f64, y: f64) -> Self { .. } } | Associated function (constructor) |
| impl Point { fn length(&self) -> f64 { .. } } | Method on struct |
| pub struct Pub { pub field: i32 } | Public struct with public field |
Iterators
| Method | Description |
|---|---|
| .iter() | Iterator of references (&T) |
| .into_iter() | Iterator that consumes collection |
| .iter_mut() | Iterator of mutable references (&mut T) |
| .map(|x| f(x)) | Transform each element |
| .filter(|x| predicate(x)) | Keep elements matching predicate |
| .collect::<Vec<_>>() | Consume iterator into collection |
| .fold(init, |acc, x| acc + x) | Reduce to single value |
| .enumerate() | Yield (index, value) pairs |
| .zip(other) | Pair elements from two iterators |
| .take(n) / .skip(n) | Limit or skip elements |
Common Macros
| Macro | Description |
|---|---|
| println!("x = {}", x) | Print with newline |
| format!("hello {name}") | Format string without printing |
| vec![1, 2, 3] | Create Vec from literal values |
| todo!() | Placeholder for unfinished code (panics) |
| unimplemented!() | Mark unimplemented branch (panics) |
| dbg!(expr) | Debug print expression and value |
| assert!(cond) | Panic if condition is false |
| assert_eq!(a, b) | Panic if a != b |
| cfg!(target_os = "linux") | Compile-time configuration check |