Skip to content

Rust Cheat Sheet — Complete Reference (60+ snippets, 2026)

Last verified May 2026 — runs in your browser
Rust Cheatsheet
let x = 5;

Immutable variable binding

Basics
let mut x = 5;

Mutable variable binding

Basics
const MAX: u32 = 100;

Compile-time constant

Basics
let x: i32 = 10;

Explicit type annotation

Basics
i8 i16 i32 i64 i128 isize u8 u16 u32 u64 u128 usize

Integer types (signed/unsigned)

Basics
f32 f64

Floating point types

Basics
let s = String::from("hello");

Heap-allocated string

Basics
let s: &str = "hello";

String slice (borrowed reference)

Basics
let arr = [1, 2, 3];

Fixed-size array

Basics
let tup: (i32, f64, &str) = (1, 2.0, "hi");

Tuple with mixed types

Basics
if condition { ... } else if other { ... } else { ... }

If/else (expression, not statement)

Basics
for item in &vec { ... }

For loop over iterator

Basics
loop { break; }

Infinite loop with explicit break

Basics
while condition { ... }

While loop

Basics
println!("x = {x}, y = {}", y);

Print with formatting macros

Basics
let s2 = s1;

Move ownership (s1 is invalid after)

Ownership
let s2 = s1.clone();

Deep copy (both remain valid)

Ownership
fn take(s: String) { ... }

Function takes ownership of arg

Ownership
fn borrow(s: &String) { ... }

Immutable borrow (reference)

Ownership
fn mutate(s: &mut String) { ... }

Mutable borrow

Ownership
let r = &x;

Create immutable reference

Ownership
let r = &mut x;

Create mutable reference

Ownership
'a

Lifetime annotation (generic lifetime)

Ownership
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str

Function with lifetime parameters

Ownership
struct User { name: String, age: u32, }

Struct definition

Structs & Enums
let u = User { name: String::from("A"), age: 30 };

Struct instantiation

Structs & Enums
impl User { fn new(name: &str) -> Self { ... } }

Method implementation block

Structs & Enums
struct Point(f64, f64);

Tuple struct

Structs & Enums
enum Color { Red, Green, Blue, Rgb(u8, u8, u8), }

Enum with variants (some with data)

Structs & Enums
enum Option<T> { Some(T), None }

Option type (nullable value)

Structs & Enums
enum Result<T, E> { Ok(T), Err(E) }

Result type (success or error)

Structs & Enums
match value { Pattern => expr, _ => default, }

Pattern matching (must be exhaustive)

Structs & Enums
if let Some(x) = optional { ... }

Destructure single pattern

Structs & Enums
#[derive(Debug, Clone, PartialEq)]

Auto-derive common traits

Structs & Enums
trait Summary { fn summarize(&self) -> String; }

Trait definition

Traits
impl Summary for Article { fn summarize(&self) -> String { ... } }

Implement trait for type

Traits
fn notify(item: &impl Summary)

Trait bound (impl syntax)

Traits
fn notify<T: Summary + Display>(item: &T)

Multiple trait bounds

Traits
fn returns() -> impl Summary

Return type implementing trait

Traits
dyn Trait

Dynamic dispatch (trait object)

Traits
Box<dyn Trait>

Heap-allocated trait object

Traits
let f = File::open("f.txt")?;

Propagate error with ? operator

Error Handling
unwrap()

Panic on Err/None (use in tests only)

Error Handling
expect("msg")

Panic with custom message on Err/None

Error Handling
unwrap_or(default)

Return default on Err/None

Error Handling
unwrap_or_else(|| compute())

Return computed default on Err/None

Error Handling
match result { Ok(val) => ..., Err(e) => ..., }

Handle Result with match

Error Handling
map_err(|e| MyError::from(e))

Transform error type

Error Handling
panic!("critical error")

Unrecoverable error (abort)

Error Handling
let v: Vec<i32> = Vec::new();

Create empty vector

Collections
let v = vec![1, 2, 3];

Create vector with values (macro)

Collections
v.push(4);

Add element to vector

Collections
v.pop();

Remove and return last element

Collections
v.iter().map(|x| x * 2).collect::<Vec<_>>()

Transform with iterator chain

Collections
v.iter().filter(|x| **x > 2).collect::<Vec<_>>()

Filter with iterator

Collections
let mut map = HashMap::new(); map.insert("key", value);

Create and populate HashMap

Collections
map.get("key")

Get value from HashMap (returns Option)

Collections
map.entry("key").or_insert(0);

Insert if key doesn't exist

Collections
let set: HashSet<i32> = HashSet::new();

Create HashSet (unique values)

Collections
use std::thread; thread::spawn(|| { ... });

Spawn a new thread

Concurrency
handle.join().unwrap();

Wait for thread to finish

Concurrency
Arc::new(Mutex::new(data))

Thread-safe shared mutable state

Concurrency
use std::sync::mpsc; let (tx, rx) = mpsc::channel();

Create message passing channel

Concurrency
tx.send(value).unwrap(); let received = rx.recv().unwrap();

Send and receive through channel

Concurrency
async fn fetch() -> Result<()> { ... }

Async function

Concurrency
let result = fetch().await?;

Await async result

Concurrency
Showing 66 of 66 snippets

Rust Cheat Sheet — Ownership, Borrowing, Lifetimes, Traits & Result/Option

Rust hit 1.0 in 2015 and has kept the same core model since: ownership and borrowing checked at compile time, no garbage collector, no null. The cheatsheet below covers 60+ snippets across basics, ownership, structs and enums, traits, error handling, collections, and concurrency. Most trouble in real Rust code doesn't come from forgetting syntax. It comes from quirks that look ordinary but bite. Passing a `String` to a function by value moves it, and the original binding stops compiling after that line. A `Box<dyn Trait>` and a generic `T: Trait` look similar at the call site but cost differently — one is heap allocation with dynamic dispatch, the other monomorphized at compile time. The `?` operator only works when the function's return type can absorb the error via a `From` conversion. The snippets below are the ones an author reaches for when debugging exactly that — the right borrow form, the right lifetime annotation, the right error conversion — without rereading the Rust reference from line one each time.

Common pitfalls in Rust

A few patterns earn their place on the first screen of any Rust file. Prefer `&str` over `&String` in function parameters when only reading text — `&str` accepts both string literals and slices of an owned `String`, while `&String` accepts only the latter. Reach for `clone()` to unblock the borrow checker temporarily, but treat each call as a question worth answering later, since cheap-looking clones on `Vec` or `String` are real allocations. The `?` operator works with `From` conversions, so defining `impl From<IoError> for MyError` lets a function returning `Result<T, MyError>` use `?` on calls that return `Result<T, IoError>` without explicit `map_err`. Async functions return a future that does nothing until awaited or polled by an executor; calling `fetch()` without `.await` starts no work. Trait objects need a `Box`, `&dyn`, or `Arc` wrapper because `dyn Trait` is unsized and cannot live on the stack on its own. The cheatsheet groups all of this into Basics, Ownership, Structs and Enums, Traits, Error Handling, Collections, and Concurrency so the right section is one click away.

  • 60+ practical Rust snippets
  • 7 categories from basics to concurrency
  • Ownership and borrowing explained
  • Error handling patterns (Result, Option)
  • One-click copy to clipboard
  • Trait system and generics covered

Free. No signup. Your inputs stay in your browser. Ads via Google AdSense (consent required).