Skip to content

Rust Cheat Sheet

A quick lookup page for things you’ll want to check without re-reading a whole lesson. Each section links back to the page that explains it properly.

Keyword Meaning
let Declare a variable (Variables)
mut Make a variable or reference mutable (Variables)
const Declare a constant (Variables)
fn Declare a function (Functions)
struct Declare a struct (Structs)
enum Declare an enum (Enums)
impl Add methods to a type (Structs, Traits)
trait Declare a trait (Traits)
match Pattern match on a value (Match)
if let / while let Match a single pattern (If Let / While Let)
loop / while / for The three loop types (Loops, While, For)
break / continue Control a loop (Break/Continue)
mod Declare a module (Modules)
pub Make an item public outside its module (Modules)
use Bring a path into scope (Modules)
unsafe Unlock raw pointers and other checked-by-you operations (Unsafe)
move Force a closure to take ownership of captured values (Concurrency)
& / &mut Borrow / mutably borrow a value (Borrowing)
Method What it does
.len() Length in bytes
.trim() Removes leading/trailing whitespace
.to_uppercase() / .to_lowercase() Case conversion
.contains(pat) Whether a substring/pattern is present
.replace(from, to) Replace all matches
.push_str(s) Append a &str
.push(c) Append a single char
.chars() Iterate character by character
.split(pat) Split into an iterator of substrings
.parse::<T>() Convert text into another type (returns Result)

See the Strings page for details and examples.

Method What it does
.push(x) Add to the end
.pop() Remove and return the last item (Option)
.remove(i) Remove the item at index i
.len() Number of items
.is_empty() Whether the vector has no items
.get(i) Safe indexed access (Option, doesn’t panic)
.iter() Iterate by reference
.contains(&x) Whether a value is present
.sort() Sort in place
.sort_by_key(|x| ...) Sort by a field or computed key
.dedup() Remove consecutive duplicates (sort first)

See the Vectors, Sorting & Searching, and Iterators pages for details and examples.

Type Use it when you need…
Vec<T> An ordered, growable list
HashMap<K, V> Fast lookup of a value by key
HashSet<T> Unique items and fast “is it in here?” checks
BTreeMap<K, V> Key-value pairs kept in sorted key order
VecDeque<T> A queue — push and pop at both ends

See the HashMaps and HashSet & BTreeMap pages for details and examples.

Method Works on What it does
.unwrap() Both Get the value, panics if None/Err
.expect("msg") Both Like .unwrap(), with a custom panic message
.unwrap_or(default) Both Get the value, or a fallback
.is_some() / .is_none() Option Check which variant it is
.is_ok() / .is_err() Result Check which variant it is
? Both Return early on None/Err

See the Option and Result pages for details and examples.

Specifier What it prints
{} Normal display (needs the Display trait)
{:?} Debug format
{:#?} Pretty-printed debug format
{:.2} 2 decimal places
{:5} Pad to a width of 5
{name} Inline a variable named name

See the Output page for details and examples.

Command What it does
cargo new name Create a new project
cargo run Build and run
cargo check Check for errors fast, without building
cargo test Run your tests
cargo add crate Add a dependency
cargo fmt Format your code
cargo clippy Lint your code for common mistakes
cargo build --release Build an optimized binary

See the Cargo & Crates page for details and examples.

Syntax Meaning
1..5 1 up to, not including, 5
1..=5 1 up to and including 5
..3 From the start up to, not including, 3
2.. From 2 to the end
.. Everything

See the For and Slices pages for details and examples.

You need… Crate Lesson
JSON (and other formats) serde + serde_json JSON with Serde
Async code, timers, networking tokio Async/Await
A command-line interface clap CLI Tool with clap
Easy error handling anyhow, thiserror anyhow & thiserror
Random numbers rand Random Numbers
Regular expressions regex Regular Expressions
Dates and times chrono Dates & Times
Logging log + env_logger, tracing Logging
A web server axum Web API with Axum

Add any of them with cargo add <crate>. See Cargo & Crates for how to choose a good crate.