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

See the Vectors and Iterators 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.

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

See the For and Slices pages for details and examples.