Rust Reference
v1.0.0Rust syntax, ownership, lifetimes, traits cheat sheet.
Quick reference cheat sheet for Rust syntax including ownership rules, lifetime annotations, trait implementations, and common patterns.
How to use- →Browse categories or search for specific syntax (e.g. "borrow", "impl", "Result") to jump to the entry.
- →Click entries to expand examples — copy the snippet and adapt it in your Rust file.
- →Use the category tabs to explore related concepts together (Ownership & Borrowing, Traits & Generics).
45 entries found
let x: T = value;
Immutable variable binding with optional type annotation.
let mut x: T = value;
Mutable variable binding — must be declared mut to reassign.
const NAME: T = value;
Compile-time constant — must have explicit type, always immutable.
i8 i16 i32 i64 i128 isize u8..u128 usize f32 f64 bool char
Primitive scalar types: signed/unsigned integers, floats, boolean, and Unicode char.
String / &str
String is an owned, heap-allocated, growable string. &str is a borrowed string slice.
let t: (T1, T2, ..) = (v1, v2, ..);
Fixed-size collection of values with potentially different types.
[T; N] / Vec<T>
Fixed-size array on the stack vs growable vector on the heap.
type Name = ExistingType;
Create a new name for an existing type.
let x = ..; let x = ..;
Re-declare a variable in the same scope — can change type.
let b = a; // a is moved
Assigning a non-Copy value moves ownership — original is invalidated.
let b = a.clone();
Deep copy — both original and clone are valid.
&T
Shared reference — multiple allowed, no mutation.
&mut T
Exclusive reference — only one at a time, allows mutation.
Either N × &T OR 1 × &mut T
At any time: multiple immutable borrows OR one mutable borrow — never both.
&[T] / &str
A reference to a contiguous sub-sequence — borrows without owning.
struct Name { field: T, .. }
Custom data type with named fields.
struct Name(T1, T2, ..);
Struct with unnamed fields — useful for newtypes.
impl Name { fn method(&self) { .. } }
Define methods and associated functions on a struct or enum.
enum Name { Variant1, Variant2(T), .. }
Algebraic data type — each variant can hold different data.
match value { Pattern => expr, .. }
Exhaustive pattern matching — must cover all variants.
Option<T> = Some(T) | None
Represents an optional value — Rust's null-safe alternative.
trait Name { fn method(&self) -> T; }
Define shared behaviour — similar to interfaces.
#[derive(Debug, Clone, PartialEq, ..)]
Auto-implement common traits via derive attribute.
fn name<T: Trait>(param: T) -> T
Write functions that work with any type satisfying a trait bound.
fn name<T>(x: T) where T: Trait + Trait2
Alternative syntax for complex trait bounds.
fn name() -> impl Trait
Return an opaque type that implements a trait — hides concrete type.
Box<dyn Trait>
Trait object — dynamic dispatch via vtable, enables heterogeneous collections.
fn name<'a>(x: &'a T) -> &'a T
Explicit lifetime — tells the compiler how long references live.
Result<T, E> = Ok(T) | Err(E)
Recoverable errors — function returns Ok on success, Err on failure.
let val = expr?;
Propagate errors — returns Err early if the result is Err.
.unwrap() / .expect("msg")
Extract the Ok/Some value — panics on Err/None. Use only when failure is impossible.
#[derive(Debug)] enum AppError { .. }
Define application-specific errors implementing std::error::Error.
panic!("message");
Unrecoverable error — unwinds the stack and terminates the thread.
thread::spawn(move || { .. })
Spawn an OS thread — use move to transfer ownership into the closure.
Arc::new(value)
Atomic reference counting — share ownership across threads.
Mutex::new(value)
Mutual exclusion — lock to get mutable access from multiple threads.
mpsc::channel() -> (Sender, Receiver)
Multi-producer, single-consumer channel for message passing.
T: Send / T: Sync
Marker traits — Send: safe to transfer to another thread. Sync: safe to share references.
.iter() / .into_iter() / .iter_mut()
Lazy iterator adaptors — chain map, filter, fold, collect.
.collect::<TargetType>()
Consume an iterator and collect results into a collection.
|params| { body }
Anonymous function that captures environment — Fn, FnMut, or FnOnce.
if let Pattern = expr { .. }
Concise pattern match for a single variant — avoids full match.
impl From<T> for U
Type conversion traits — implementing From gives Into for free.
impl fmt::Display for T
Custom formatting for println! and format! macros.
Builder::new().field(v).build()
Construct complex objects step by step with method chaining.