let x = 5; Immutable variable binding
let mut x = 5; Mutable variable binding
const MAX: u32 = 100; Compile-time constant
let x: i32 = 10; Explicit type annotation
i8 i16 i32 i64 i128 isize
u8 u16 u32 u64 u128 usize Integer types (signed/unsigned)
f32 f64 Floating point types
let s = String::from("hello"); Heap-allocated string
let s: &str = "hello"; String slice (borrowed reference)
let arr = [1, 2, 3]; Fixed-size array
let tup: (i32, f64, &str) = (1, 2.0, "hi"); Tuple with mixed types
if condition {
...
} else if other {
...
} else {
...
} If/else (expression, not statement)
for item in &vec { ... } For loop over iterator
loop { break; } Infinite loop with explicit break
while condition { ... } While loop
println!("x = {x}, y = {}", y); Print with formatting macros
let s2 = s1; Move ownership (s1 is invalid after)
let s2 = s1.clone(); Deep copy (both remain valid)
fn take(s: String) { ... } Function takes ownership of arg
fn borrow(s: &String) { ... } Immutable borrow (reference)
fn mutate(s: &mut String) { ... } Mutable borrow
let r = &x; Create immutable reference
let r = &mut x; Create mutable reference
'a Lifetime annotation (generic lifetime)
fn longest<'a>(a: &'a str, b: &'a str) -> &'a str Function with lifetime parameters
struct User {
name: String,
age: u32,
} Struct definition
let u = User { name: String::from("A"), age: 30 }; Struct instantiation
impl User {
fn new(name: &str) -> Self { ... }
} Method implementation block
struct Point(f64, f64); Tuple struct
enum Color {
Red,
Green,
Blue,
Rgb(u8, u8, u8),
} Enum with variants (some with data)
enum Option<T> { Some(T), None } Option type (nullable value)
enum Result<T, E> { Ok(T), Err(E) } Result type (success or error)
match value {
Pattern => expr,
_ => default,
} Pattern matching (must be exhaustive)
if let Some(x) = optional { ... } Destructure single pattern
#[derive(Debug, Clone, PartialEq)] Auto-derive common traits
trait Summary {
fn summarize(&self) -> String;
} Trait definition
impl Summary for Article {
fn summarize(&self) -> String { ... }
} Implement trait for type
fn notify(item: &impl Summary) Trait bound (impl syntax)
fn notify<T: Summary + Display>(item: &T) Multiple trait bounds
fn returns() -> impl Summary Return type implementing trait
dyn Trait Dynamic dispatch (trait object)
Box<dyn Trait> Heap-allocated trait object
let f = File::open("f.txt")?; Propagate error with ? operator
unwrap() Panic on Err/None (use in tests only)
expect("msg") Panic with custom message on Err/None
unwrap_or(default) Return default on Err/None
unwrap_or_else(|| compute()) Return computed default on Err/None
match result {
Ok(val) => ...,
Err(e) => ...,
} Handle Result with match
map_err(|e| MyError::from(e)) Transform error type
panic!("critical error") Unrecoverable error (abort)
let v: Vec<i32> = Vec::new(); Create empty vector
let v = vec![1, 2, 3]; Create vector with values (macro)
v.push(4); Add element to vector
v.pop(); Remove and return last element
v.iter().map(|x| x * 2).collect::<Vec<_>>() Transform with iterator chain
v.iter().filter(|x| **x > 2).collect::<Vec<_>>() Filter with iterator
let mut map = HashMap::new();
map.insert("key", value); Create and populate HashMap
map.get("key") Get value from HashMap (returns Option)
map.entry("key").or_insert(0); Insert if key doesn't exist
let set: HashSet<i32> = HashSet::new(); Create HashSet (unique values)
use std::thread;
thread::spawn(|| { ... }); Spawn a new thread
handle.join().unwrap(); Wait for thread to finish
Arc::new(Mutex::new(data)) Thread-safe shared mutable state
use std::sync::mpsc;
let (tx, rx) = mpsc::channel(); Create message passing channel
tx.send(value).unwrap();
let received = rx.recv().unwrap(); Send and receive through channel
async fn fetch() -> Result<()> { ... } Async function
let result = fetch().await?; Await async result
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).