Skip to content
Tutorials Center
My learning

Topics

Lesson 126 of 132 ยท Practice and Review

Rust Cheat Sheet

A one-page Rust cheat sheet for Rust 1.99: syntax, ownership rules, common traits, collections, iterator adapters, error handling and a compiler error index.

This page is a compact reference for Rust 1.99 (edition 2024): the syntax and standard library features you use every day, in one place. It is not a tutorial. Each section links to the lesson that explains the topic in depth, and the trickiest items have a small program you can run and change. Code blocks without a Run button are read-only fragments that you place inside a function.

Keep it open while you work, and use the search box (Ctrl+K) for anything that is not here. When you want practice rather than reference, try the fundamentals problems or the advanced problems. When the compiler says something puzzling, Reading Compiler Errors walks through the common messages.

Program structure

See Getting Started, Syntax and Printing.

Rust
use std::collections::HashMap; // bring a name into scope

const MAX_USERS: u32 = 100; // constants need a type and a constant value
static GREETING: &str = "hi"; // one fixed address for the whole program

fn main() {
    let name = "Ferris"; // immutable binding
    println!("Hello, {name}! {MAX_USERS} {GREETING}"); // {name} captures a variable
}

Everything is an expression or a statement. A block's value is its last expression without a semicolon; adding a semicolon turns it into a statement and the block returns ().

Rust The last expression is the value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Variables and types

See Variables, Scalar Types and Numeric Conversion.

Item Syntax Notes
Immutable let x = 5; Cannot be reassigned
Mutable let mut x = 5; x += 1 allowed
Shadowing let x = x * 2; New variable, may change type
Integers i8 i16 i32 i64 i128 isize, u8 u16 u32 u64 u128 usize Default is i32
Floats f32 f64 Default is f64
Others bool, char (4 bytes, a Unicode scalar), () 'a' is a char, "a" is a &str
Tuple (i32, &str), t.0 Fixed size, mixed types
Array [i32; 3], [0; 8] Fixed length, on the stack
Slice &[i32], &v[1..3] Borrowed view with a length
Casting x as u8 Truncates silently, so prefer u8::try_from(x)

Integer overflow panics in debug builds (which is what our editor runs) and wraps in release builds. Say what you mean with checked_add, wrapping_add, saturating_add or overflowing_add.

Control flow

See Operators, if Expressions, match, Loops and Patterns.

Rust
let size = if n < 10 { "small" } else { "large" };

for i in 0..3 {}          // 0, 1, 2
for i in 0..=3 {}         // 0, 1, 2, 3
for (i, c) in "abc".chars().enumerate() {}
while n > 0 { n -= 1; }
let found = loop { break 42; }; // loop can return a value
'outer: for a in 0..3 { for b in 0..3 { if b == 1 { continue 'outer; } } }

match n {
    0 => println!("zero"),
    1 | 2 => println!("one or two"),
    3..=9 => println!("small"),
    x if x < 0 => println!("negative"),
    _ => println!("big"),
}

if let Some(v) = opt { /* use v */ }
if let Some(v) = opt && v > 3 { /* let chains: edition 2024 */ }
let Some(v) = opt else { return; }; // let-else: must diverge

match must be exhaustive: the compiler rejects a missing case. if let ... && ... chains need edition 2024 (Rust 1.88).

Ownership and borrowing

See Ownership, Borrowing, Lifetimes and Copy and Clone.

The rules in one place:

  1. Every value has exactly one owner.
  2. When the owner goes out of scope, the value is dropped.
  3. Assigning or passing a non-Copy value moves it; the old name is dead.
  4. At any moment you may have either any number of shared references (&T) or exactly one mutable reference (&mut T), never both.
  5. A reference may never outlive the value it points to.
You write Meaning
let b = a; Move (or copy, if the type is Copy)
let b = a.clone(); Explicit deep copy
f(&a) Lend read-only access
f(&mut a) Lend exclusive write access (needs let mut a)
fn f<'a>(x: &'a str) -> &'a str The result lives no longer than x
&'static str Valid for the whole program (string literals)

Copy types (integers, floats, bool, char, tuples and arrays of Copy types, shared references) are duplicated on assignment. String, Vec, Box and your own structs are moved unless you derive Copy.

Rust Move, borrow, mutate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Structs, enums and methods

See Structs, Methods, Enums and Enums and match.

Rust
#[derive(Debug, Clone, PartialEq)]
struct Point { x: f64, y: f64 }          // named fields
struct Meters(f64);                       // tuple struct (newtype)
struct Marker;                            // unit struct

impl Point {
    const ORIGIN: Point = Point { x: 0.0, y: 0.0 };
    fn new(x: f64, y: f64) -> Self { Self { x, y } }   // associated function
    fn norm(&self) -> f64 { (self.x * self.x + self.y * self.y).sqrt() } // &self: read
    fn shift(&mut self, dx: f64) { self.x += dx; }                       // &mut self: write
    fn into_pair(self) -> (f64, f64) { (self.x, self.y) }                // self: consume
}

enum Shape { Circle(f64), Rect { w: f64, h: f64 }, Empty }

Struct update syntax: Point { x: 1.0, ..other }. Field init shorthand: Point { x, y }.

Traits and generics

See Traits, Generics, Trait Bounds and Trait Objects.

Rust
trait Speak {
    fn name(&self) -> String;
    fn hello(&self) -> String { format!("I am {}", self.name()) } // default method
}

fn greet(x: &impl Speak) {}                       // static dispatch (sugar for a generic)
fn greet2<T: Speak + Clone>(x: &T) {}             // bounds
fn greet3<T>(x: &T) where T: Speak + std::fmt::Debug {}
fn make() -> impl Iterator<Item = u32> { 0..3 }   // return an unnameable type
fn dynamic(x: &dyn Speak) {}                      // dynamic dispatch (vtable)
let boxed: Vec<Box<dyn Speak>> = Vec::new();      // heterogeneous collection

Static dispatch (impl Trait, generics) is monomorphized: fast, but one copy of the code per type. dyn Trait is one copy plus an indirect call, and the trait must be object safe.

Traits you will meet constantly

Trait What it gives you How
Debug {:?} printing #[derive(Debug)]
Display {} printing, .to_string() Implement by hand
Clone / Copy Explicit / implicit duplication derive
PartialEq / Eq ==; Eq marks it total (not for floats) derive
PartialOrd / Ord <, sort(), max() derive
Hash Use as a HashMap key derive
Default T::default(), ..Default::default() derive
From / Into Infallible conversion implement From
TryFrom / TryInto Fallible conversion implement TryFrom
FromStr "42".parse::<T>() implement by hand
Iterator for loops and adapters implement next
Drop Cleanup at scope end implement by hand
Deref Smart pointer behaviour implement by hand
Send / Sync Safe to move / share across threads automatic
Error Standard error trait implement with Display + Debug

See Display and From, Send and Sync and Operator Overloading.

Strings

See Strings Overview and Strings.

Type Owns data? Use for
String Yes, growable, UTF-8 Building and storing text
&str No, a view Function parameters, literals
char Yes, one Unicode scalar Single characters
OsString/Path Yes/No File names

s.len() counts bytes, not characters. Use s.chars().count() for scalar values, and never slice at an arbitrary byte index (&s[0..1] panics in the middle of a multi-byte character).

Rust Bytes versus characters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Collections

See Vec, HashMap and Other Collections.

Collection Create Common operations
Vec<T> vec![1, 2, 3], Vec::new() push, pop, insert, remove, len, iter, sort, dedup, retain, extend
HashMap<K, V> HashMap::new() insert, get, entry(k).or_insert(v), remove, contains_key, keys, values
BTreeMap<K, V> BTreeMap::new() Same API, keys always sorted
HashSet<T> / BTreeSet<T> HashSet::new() insert, contains, union, intersection, difference
VecDeque<T> VecDeque::new() push_back, push_front, pop_front, pop_back
BinaryHeap<T> BinaryHeap::new() push, pop (largest first), peek

HashMap and HashSet iterate in a random order that changes from run to run. Sort the keys or use the BTree versions when order matters. Index access v[10] panics when out of range; v.get(10) returns an Option.

Iterators and closures

See Iterators, Iterator Patterns and Closures.

Iterators are lazy: nothing happens until a consumer runs.

Make one Adapt (lazy) Consume
v.iter() (items are &T) map(f), filter(p), filter_map(f) collect::<Vec<_>>()
v.iter_mut() (items are &mut T) enumerate(), zip(other), rev() sum(), product(), count()
v.into_iter() (items are T) take(n), skip(n), step_by(n) min(), max(), min_by_key(f)
a..b, a..=b chain(other), flatten(), flat_map(f) fold(init, f), reduce(f)
s.chars(), s.bytes(), s.lines() take_while(p), skip_while(p), peekable() any(p), all(p), find(p), position(p)
std::iter::repeat_n(x, n), successors, from_fn windows(n), chunks(n), chunk_by(f) (on slices) for_each(f), last(), nth(n)
Rust A small adapter pipeline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Closures: |x| x + 1, |a, b| a * b, move |x| x + offset (takes ownership of captured variables, required when a closure outlives its scope, for example in a thread). The traits are Fn (borrows), FnMut (mutates) and FnOnce (consumes); every closure implements at least FnOnce.

Error handling

See Option, Result, The ? Operator, Custom Errors and Error Design.

Rust
let n: i32 = "42".parse()?;                 // return the Err early, unwrap the Ok
let n = "x".parse::<i32>().unwrap_or(0);    // default on failure
let n = opt.ok_or("missing")?;              // Option to Result
let r = res.map_err(|e| MyError::Parse(e))?; // change the error type
let len = opt.map(|s| s.len()).unwrap_or_default();
let v = opt.expect("config must exist");    // panic with a message (bugs only)
Situation Use
A value may be absent Option<T>
An operation may fail and the caller can react Result<T, E>
A bug or broken invariant panic!, assert!, unreachable!
Quick demo or test unwrap() / expect()
A library A dedicated error enum implementing Display and Error
An application Box<dyn Error> (or the anyhow crate)

? works in any function that returns Result or Option (and fn main() -> Result<(), Box<dyn Error>>). It calls From::from on the error, which is how a ParseIntError becomes your own error type.

Rust The ? operator with a mixed error type

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.

Smart pointers and shared state

See Smart Pointers, Rc and Arc and RefCell and Cell.

Type What it is Thread-safe?
Box<T> One owner, value on the heap If T is
Rc<T> Shared ownership by reference counting No
Arc<T> Same as Rc, with atomic counts Yes
Cell<T> / RefCell<T> Mutation through &, checked at run time No
Mutex<T> / RwLock<T> Locked mutation Yes
Cow<'a, T> Borrow until you need to modify If T is

The usual combinations are Rc<RefCell<T>> on one thread and Arc<Mutex<T>> across threads.

Concurrency

See Threads, Channels, Mutex and RwLock and Atomics.

Rust
let handle = std::thread::spawn(move || compute());   // 'static closure
let value = handle.join().unwrap();                    // wait for the result

std::thread::scope(|s| {                               // borrow locals safely
    s.spawn(|| println!("{}", data.len()));
});

let (tx, rx) = std::sync::mpsc::channel();             // message passing
let shared = std::sync::Arc::new(std::sync::Mutex::new(0)); // shared state

Modules and Cargo

See Modules, Cargo and Projects and Crates and Dependencies.

TEXT
cargo new hello        # create a project
cargo run              # build (debug) and run
cargo run --release    # optimized build
cargo check            # type-check only, fast
cargo test             # run unit, integration and doc tests
cargo fmt              # format with rustfmt
cargo clippy           # lints
cargo doc --open       # build and open the docs
cargo add serde        # add a dependency

Visibility is private by default: pub exposes an item, pub(crate) limits it to the crate. mod name { } declares a module, use imports, and crate::, self:: and super:: start a path. Our in-browser editor compiles a single main.rs with the standard library only, so crates such as serde or tokio are shown read-only in these lessons.

Compiler error index

When a message has a code, read it in full: the text under the arrow and the help: lines usually contain the fix. Reading Compiler Errors shows each of these failing on purpose.

Code Plain meaning Usual fix
E0382 Use of a moved value Borrow it, clone() it, or restructure
E0499 Two &mut borrows alive at once Shorten the first borrow, split the data
E0502 & and &mut alive at once Finish reading before writing
E0505 Moved out while borrowed Let the borrow end first
E0506 Assigned to a borrowed value Same as above
E0308 Mismatched types Convert, or fix the signature
E0277 A trait bound is not satisfied Derive or implement the trait, or change the type
E0599 No such method for this type Check the type, import the trait, add a derive
E0106 Missing lifetime specifier Add 'a, or return an owned value
E0425 Unresolved name Typo, missing use, or out of scope
E0384 Assigned twice to an immutable variable Add mut
E0596 Cannot borrow as mutable Declare let mut, take &mut
E0597 Value does not live long enough Move the owner to an outer scope
E0004 Non-exhaustive match Add the missing arms or _
E0373 Closure may outlive the function Add move

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a block evaluate to when its last line ends with a semicolon?

    A trailing semicolon turns the last expression into a statement, so the block's value is (). That is why n * n; as the last line of a function returning i32 is an error.
  2. 2. Which rule decides when a String is freed?

    Ownership means exactly one owner, and the value is dropped when that owner goes out of scope. Reference counting only applies when you choose Rc or Arc.
  3. 3. Which combination is allowed at one moment for the same value?

    Shared references can coexist with each other, and a mutable reference must be the only access. Mixing them is rejected with E0502 (or E0499 for two mutable ones).
  4. 4. What does "hรฉllo".len() return?

    len() counts bytes. The letter รฉ takes two bytes in UTF-8, so the string has 6 bytes but 5 characters (chars().count()).
  5. 5. Which type is the right choice for sharing mutable state between threads?

    Arc gives thread-safe shared ownership and Mutex gives locked mutation. Rc and RefCell are not Send or Sync, so the compiler rejects them across threads.

Summary

  • A block's value is its last expression without a semicolon; match must be exhaustive.
  • One owner per value, moves by default, Copy for small plain types, borrow with & or &mut but never both at once.
  • String owns text, &str borrows it, and len() counts bytes.
  • Iterator adapters are lazy; a consumer such as collect, sum or for starts the work.
  • Use Option for absence, Result for recoverable failure, ? to propagate, and panic! only for bugs.
  • Arc<Mutex<T>> shares state across threads; Rc<RefCell<T>> does it on one thread.
  • Read the error code and the help: text; most messages explain their own fix.

Next: Reading Compiler Errors