Skip to main content

Rust Reference

v1.0.0

Rust 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 binding
Variables & Types

let x: T = value;

Immutable variable binding with optional type annotation.

let mut
Variables & Types

let mut x: T = value;

Mutable variable binding — must be declared mut to reassign.

const
Variables & Types

const NAME: T = value;

Compile-time constant — must have explicit type, always immutable.

Scalar types
Variables & Types

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 vs &str
Variables & Types

String / &str

String is an owned, heap-allocated, growable string. &str is a borrowed string slice.

Tuple
Variables & Types

let t: (T1, T2, ..) = (v1, v2, ..);

Fixed-size collection of values with potentially different types.

Array / Vec
Variables & Types

[T; N] / Vec<T>

Fixed-size array on the stack vs growable vector on the heap.

Type alias
Variables & Types

type Name = ExistingType;

Create a new name for an existing type.

Shadowing
Variables & Types

let x = ..; let x = ..;

Re-declare a variable in the same scope — can change type.

Ownership move
Ownership & Borrowing

let b = a; // a is moved

Assigning a non-Copy value moves ownership — original is invalidated.

Clone
Ownership & Borrowing

let b = a.clone();

Deep copy — both original and clone are valid.

Immutable borrow
Ownership & Borrowing

&T

Shared reference — multiple allowed, no mutation.

Mutable borrow
Ownership & Borrowing

&mut T

Exclusive reference — only one at a time, allows mutation.

Borrowing rules
Ownership & Borrowing

Either N × &T OR 1 × &mut T

At any time: multiple immutable borrows OR one mutable borrow — never both.

Slice
Ownership & Borrowing

&[T] / &str

A reference to a contiguous sub-sequence — borrows without owning.

struct
Structs & Enums

struct Name { field: T, .. }

Custom data type with named fields.

Tuple struct
Structs & Enums

struct Name(T1, T2, ..);

Struct with unnamed fields — useful for newtypes.

impl block
Structs & Enums

impl Name { fn method(&self) { .. } }

Define methods and associated functions on a struct or enum.

enum
Structs & Enums

enum Name { Variant1, Variant2(T), .. }

Algebraic data type — each variant can hold different data.

match
Structs & Enums

match value { Pattern => expr, .. }

Exhaustive pattern matching — must cover all variants.

Option<T>
Structs & Enums

Option<T> = Some(T) | None

Represents an optional value — Rust's null-safe alternative.

trait
Traits & Generics

trait Name { fn method(&self) -> T; }

Define shared behaviour — similar to interfaces.

Derive macros
Traits & Generics

#[derive(Debug, Clone, PartialEq, ..)]

Auto-implement common traits via derive attribute.

Generic function
Traits & Generics

fn name<T: Trait>(param: T) -> T

Write functions that work with any type satisfying a trait bound.

where clause
Traits & Generics

fn name<T>(x: T) where T: Trait + Trait2

Alternative syntax for complex trait bounds.

impl Trait
Traits & Generics

fn name() -> impl Trait

Return an opaque type that implements a trait — hides concrete type.

dyn Trait
Traits & Generics

Box<dyn Trait>

Trait object — dynamic dispatch via vtable, enables heterogeneous collections.

Lifetime annotation
Traits & Generics

fn name<'a>(x: &'a T) -> &'a T

Explicit lifetime — tells the compiler how long references live.

Result<T, E>
Error Handling

Result<T, E> = Ok(T) | Err(E)

Recoverable errors — function returns Ok on success, Err on failure.

? operator
Error Handling

let val = expr?;

Propagate errors — returns Err early if the result is Err.

unwrap / expect
Error Handling

.unwrap() / .expect("msg")

Extract the Ok/Some value — panics on Err/None. Use only when failure is impossible.

Custom error type
Error Handling

#[derive(Debug)] enum AppError { .. }

Define application-specific errors implementing std::error::Error.

panic!
Error Handling

panic!("message");

Unrecoverable error — unwinds the stack and terminates the thread.

std::thread::spawn
Concurrency

thread::spawn(move || { .. })

Spawn an OS thread — use move to transfer ownership into the closure.

Arc<T>
Concurrency

Arc::new(value)

Atomic reference counting — share ownership across threads.

Mutex<T>
Concurrency

Mutex::new(value)

Mutual exclusion — lock to get mutable access from multiple threads.

mpsc channel
Concurrency

mpsc::channel() -> (Sender, Receiver)

Multi-producer, single-consumer channel for message passing.

Send + Sync
Concurrency

T: Send / T: Sync

Marker traits — Send: safe to transfer to another thread. Sync: safe to share references.

Iterator
Common Patterns

.iter() / .into_iter() / .iter_mut()

Lazy iterator adaptors — chain map, filter, fold, collect.

collect()
Common Patterns

.collect::<TargetType>()

Consume an iterator and collect results into a collection.

Closure
Common Patterns

|params| { body }

Anonymous function that captures environment — Fn, FnMut, or FnOnce.

if let / while let
Common Patterns

if let Pattern = expr { .. }

Concise pattern match for a single variant — avoids full match.

From / Into
Common Patterns

impl From<T> for U

Type conversion traits — implementing From gives Into for free.

Display trait
Common Patterns

impl fmt::Display for T

Custom formatting for println! and format! macros.

Builder pattern
Common Patterns

Builder::new().field(v).build()

Construct complex objects step by step with method chaining.