Rust Cheatsheet

Rust ownership, borrowing, lifetimes, Option/Result, traits, and iterators reference

The Rust cheatsheet covers ownership rules, borrowing, String vs &str, Option/Result with the ? operator, pattern matching, traits, closures, and iterators. Focused on concepts that trip up newcomers.

How to Use This Rust Cheatsheet

Rust is a systems programming language focused on safety, speed, and concurrency. Its ownership system prevents memory bugs at compile time, making it unique among modern languages. This cheatsheet focuses on patterns that newcomers find most challenging.

The Borrow Checker

The borrow checker enforces: at any time, you can have either one mutable reference OR any number of immutable references, never both simultaneously. This prevents data races at compile time. If you're fighting the borrow checker, consider restructuring to use ownership transfer instead of references.

Option and Result

Option<T> is Some(value) or None. Result<T, E> is Ok(value) or Err(error). Use the ? operator to propagate errors up the call stack. Use .unwrap_or(default) for safe defaults.

Iterator Chains

Rust iterators are lazy and zero-cost. vec.iter().filter(|x| **x > 5).map(|x| x * 2).collect() compiles to efficient loop code. Learn map, filter, fold, collect, any, all, flat_map — they replace most explicit loops.

Frequently Asked Questions

Is this Rust cheatsheet free?

Yes, completely free with no signup. All code examples are copyable.

What is Rust ownership?

Rust's ownership system ensures memory safety without a garbage collector. Each value has exactly one owner. When the owner goes out of scope, the value is dropped. You can transfer ownership (move) or create references (borrow). This prevents dangling pointers, double frees, and data races at compile time.

What is the difference between String and &str in Rust?

String is an owned, heap-allocated, growable string. &str is a string slice — a reference into some string data (stack, heap, or binary). Functions that only need to read a string should take &str (more flexible). Functions that need to own or modify the string take String. Convert with to_string() or to_owned().

What is the ? operator in Rust?

The ? operator is shorthand for error propagation. In a function returning Result<T,E>, writing value? will: unwrap Ok(value) to continue, or return Err(e) immediately from the function. It replaces verbose match Ok(v) => v, Err(e) => return Err(e) patterns. The function must return Result (or Option).

What are Rust traits?

Traits are Rust's interfaces — they define shared behavior across types. Implement a trait with impl TraitName for MyType. Use trait bounds in generics: fn print<T: Display>(val: T) only accepts types that implement Display. Common traits: Debug, Display, Clone, Copy, Iterator, From, Into.