Rust: enums, traits, errors and iterators

The Rust that replaces Python's None checks, exceptions, duck typing and generators: text as UTF-8 bytes, enums with data and exhaustive match, Option, Result and ?, traits and generics, iterators and closures, the collections, and cargo's built-in tests. Every output and compiler error is a real run (rustc 1.99.0, CPython 3.14.8) on an Apple M1 Pro, except the enum layout and iterator trace runs added in November 2026 (rustc 1.94.0, Linux x86-64). A child of Rust: the essentials. Data as of October 2026. Reading: 39 min, plus 18 in closed details.

Rust turns what a Python program discovers while it runs into types the compiler checks before it runs: an enum says exactly which data each case carries and match must handle every case, Result puts every failure in the signature, a trait says what a type can do, and the iterator chains built on all of this compile to the same machine code as the loop you would have written by hand.

You need: Cargo, ownership, moves and borrowing (& and &mut) from Rust: the essentials. Lifetimes, Box, Rc and threads are on Rust: lifetimes, smart pointers, threads and unsafe; this page mentions them only where a type here needs one.

Slice, &str
a borrowed view (pointer and length) into elements or UTF-8 text owned by someone else.
Enum, variant
a type that is exactly one of several cases (variants), each carrying its own fields: a sum type or tagged union.
match
takes a value apart by pattern; it must cover every variant (exhaustive).
Option, Result
the standard enums for "maybe missing" (Some, None) and "may fail" (Ok, Err).
?
"if this is an error, return it from my function now; otherwise give me the value".
Trait, bound
a named set of methods a type promises; T: Tokenizer limits a generic to types that implement it.
Monomorphisation, vtable
one compiled copy of a generic per type, against one copy that calls through a table of function pointers.
Closure, Fn, FnMut, FnOnce
an anonymous function that captures variables; the three traits say whether it reads, changes or consumes them.

The same four mistakes: Python finds them while running, Rust before running

The Rust side of each row is a recorded run on this page: a missing match arm is error E0004 (section 2); a maybe-missing value is an Option and a failed parse of "8k" a Result, and you get the value inside only by deciding what happens in the other case (section 3); a type without the trait is E0277 at the call (section 4). The Python side is what the same mistake does in plain Python with no type checker. One exception stays a run-time failure in Rust too: a string slice that cuts a character panics (section 1). And the price of all this checking in a hot loop is none: an iterator chain ran at 0.293 ns per element, the hand-written loop at 0.290 (section 5) measured.

In one screen

In PythonIn RustWhat changes for youSection
str, len in code pointsString (owned) and &str (borrowed), lengths in bytesslice at character boundaries; iterate with chars()1
a class with optional fields and a status stringan enum whose variants carry their own dataimpossible states cannot be written; a new case lists every match to update2
None anywhere, exceptionsOption, Result, ?; panic! for bugsevery failure is in the signature3
duck typing, Protocoltraits, generics with bounds, dyn Traitchecked at compile time; generics cost nothing, dyn an indirect call4
generators, comprehensions, lambdaiterator adapters, collect, closuresthe same laziness, at the speed of a hand-written loop5
list, dict, set, deque, heapqVec, HashMap, HashSet, VecDeque, BinaryHeapHashMap order is random per run6
pytestcargo test: unit, integration and doc testsnothing to install; doc examples are compiled and run7

How to read the code: each block is a file in this page's src/ra/code/, followed by the command that ran and its real output (green border) or error (orange border). Dashed boxes are predictions: the Python and three Rust translations a newcomer might write; pick one, then see what all three did. Recorded 2026-10-05 with rustc 1.99.0 (edition 2024) and CPython 3.14.8.

1. Strings and slices: String against &str, and UTF-8

A slice is a borrowed view into a run of elements owned by someone else: a pointer and a length. &[u64] is a slice of numbers (borrowed from a Vec, an array or part of either); &str is a slice of text. Rust has two main string types:

String&str
Whatowned, growable text on the heapa borrowed view of text (in a String, a literal, a file buffer)
Size on the stack24 bytes (pointer, capacity, length)16 bytes (pointer, length)
Use forstruct fields, return values, building textfunction parameters that only read
Make oneString::from("x"), "x".to_string(), format!(...)&s, &s[a..b], "literal"

Both are always valid UTF-8, and lengths and indexes are in bytes; Python's str counts code points. The figure uses the text of the recorded program: 10 characters, 20 bytes.

strings.rs
fn count_words(text: &str) -> usize {
    // &str accepts a String (via &s) and a literal alike
    text.split_whitespace().count()
}

fn main() {
    let s = String::from("café 日本語 🦀");
    println!("len() = {} bytes", s.len());
    println!("chars = {}", s.chars().count());
    println!("bytes of 'é': {:?}", "é".as_bytes());
    println!("&s[0..3] = {:?}", &s[0..3]); // byte offsets
    println!("first char = {:?}", s.chars().next());
    println!("char_indices: {:?}", s.char_indices().map(|(i, _)| i).collect::<Vec<_>>());
    let mut owned = String::new(); // String: owned, growable, on the heap
    owned.push_str("tokens");
    owned += " and logits";
    let view: &str = &owned[0..6]; // &str: a borrowed view (pointer + length)
    println!("{owned} | {view} | words {}", count_words(&owned) + count_words("a literal is a &str"));
    println!("size_of String = {}, &str = {}", std::mem::size_of::<String>(), std::mem::size_of::<&str>());
    println!("upper: {}", s.to_uppercase());
    println!("reversed chars: {}", s.chars().rev().collect::<String>());
    let cut = &s[0..4]; // 'é' occupies bytes 3 and 4: this panics at run time
    println!("{cut}");
}
$ rustc --edition 2024 strings.rs && ./strings
len() = 20 bytes
chars = 10
bytes of 'é': [195, 169]
&s[0..3] = "caf"
first char = Some('c')
char_indices: [0, 1, 2, 3, 5, 6, 9, 12, 15, 16]
tokens and logits | tokens | words 8
size_of String = 24, &str = 16
upper: CAFÉ 日本語 🦀
reversed chars: 🦀 語本日 éfac

thread 'main' (16490040) panicked at strings.rs:22:17:
end byte index 4 is not a char boundary; it is inside 'é' (bytes 3..5 of string)
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
[exit code 101]
$ python3.14 strings.py
len(s) = 10 code points
utf-8 bytes = 20
s[0:4] = 'café'
  • len() is 20 bytes for 10 characters; Python's len is 10. Slicing takes byte offsets and panics if one lands inside a character, as the last line shows. Iterate with chars() (code points) or char_indices() (code points with their byte offsets).
  • s[0] does not compile at all, because a byte index would not give a character: E0277, "the type str cannot be indexed by {integer}", with the hint to use .chars().nth() or .bytes().nth().
The full E0277 error for s[0]
$ rustc --edition 2024 index_err.rs
error[E0277]: the type `str` cannot be indexed by `{integer}`
 --> index_err.rs:3:15
  |
3 |     let c = s[0];
  |               ^ string indices are ranges of `usize`
  |
  = help: the trait `SliceIndex<str>` is not implemented for `{integer}`
  = note: you can use `.chars().nth()` or `.bytes().nth()`
          for more information, see chapter 8 in The Book: <https://doc.rust-lang.org/book/ch08-02-strings.html#indexing-into-strings>
help: `usize` implements trait `SliceIndex<T>`
 --> /rustc/b940084d7eb6a299eb4bfeb8e34901bc051e7ac4/library/core/src/slice/index.rs:179:0
  |
  = note: `SliceIndex<[T]>`
 --> /rustc/b940084d7eb6a299eb4bfeb8e34901bc051e7ac4/library/core/src/bstr/traits.rs:197:0
  |
  = note: `SliceIndex<ByteStr>`
  = note: required for `String` to implement `Index<{integer}>`

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0277`.
[exit code 1]

Take &str in parameters (count_words(text: &str) accepts &owned and a literal alike; clippy's ptr_arg lint flags &String parameters) and return String when you build new text. A "character" a user sees may be several code points (an emoji with a skin tone); neither language's len counts those.

A slice must end on a character boundary: drag the end and watch which cuts are allowed

Predict first: of the 21 possible end offsets (0 to 20), how many can &s[0..end] use without panicking?

Cells are the 20 UTF-8 bytes of "café 日本語 🦀", grouped under the character they encode: é takes 2 bytes, each of 日本語 3, the crab 4. The allowed ends are exactly the 10 offsets char_indices() printed (0, 1, 2, 3, 5, 6, 9, 12, 15, 16) plus 20, the end of the string: 11 of 21. At end 4 the message is the one the recorded program printed; the other positions apply the same rule in your browser.

Predict: Length of a string. Which Rust version prints what the Python prints?
d04.py
print(len("naïve"))
$ python3.14 d04.py
5
A
d04_a.rs
fn main() {
    println!("{}", "naïve".len());
}
B
d04_b.rs
fn main() {
    println!("{}", "naïve".chars().count());
}
C
d04_c.rs
fn main() {
    println!("{}", "naïve".bytes().count());
}
What the three really did (rustc 1.99.0, debug builds)
A: compiles and runs, differs. len() is the number of UTF-8 bytes; ï takes 2.
$ rustc --edition 2024 d04_a.rs && ./d04_a
6
B: compiles and runs, matches Python. Python's len counts code points, which are Rust's chars.
$ rustc --edition 2024 d04_b.rs && ./d04_b
5
C: compiles and runs, differs. The same as len(): bytes.
$ rustc --edition 2024 d04_c.rs && ./d04_c
6

2. Structs, enums and match: make illegal states unrepresentable

A struct is a record with named fields, like a dataclass. An enum in Rust is far more than Python's Enum: each variant can carry its own data, so one type says "a message is either text from a user, or a tool call with arguments, or an image of some size". This is called a sum type or tagged union. match takes it apart, and must cover every variant.

The design habit this enables matters more than the syntax. Python code often models state as one class with optional fields and a status string, and every method checks that the fields agree with the status. In Rust, give each state exactly the data it has. "Connected but no session id" or "failed with no error" then cannot be written at all:

states.rs (lines 1 to 20)
// Python habit: one class with optional fields and a status string.
// Here every state carries exactly the data that state has, so
// "connected but no socket" or "failed but no error" cannot be written.
#[derive(Debug)]
enum Conn {
    Idle,
    Connecting { attempt: u32 },
    Connected { session_id: u64 },
    Failed { error: String },
}

fn step(c: Conn) -> Conn {
    match c {
        Conn::Idle => Conn::Connecting { attempt: 1 },
        Conn::Connecting { attempt } if attempt < 3 => Conn::Connecting { attempt: attempt + 1 },
        Conn::Connecting { .. } => Conn::Connected { session_id: 42 },
        Conn::Connected { session_id } => Conn::Connected { session_id },
        Conn::Failed { error } => Conn::Failed { error },
    }
}
$ rustc --edition 2024 states.rs && ./states
Idle
Connecting { attempt: 1 }
Connecting { attempt: 2 }
Connecting { attempt: 3 }
Connected { session_id: 42 }
Failed { error: "timeout" }
size_of Option<u64> = 16
size_of Option<&u64> = 8
size_of Option<Box<u64>> = 8

The same connection, two ways: 32 states you can write, 4 that make sense

Counting only the four status strings the code uses, a class with status and three optional fields (attempt, session_id, error) can hold 4 × 2 × 2 × 2 = 32 combinations; 4 are legal. The Rust enum is code/lang/states.rs below; the Python class is illustrative, not run.

What an enum costs in memory

The last three lines of that run are about memory: Option<u64> needs 16 bytes, but Option<&u64> and Option<Box<u64>> fit in 8. A second program, layout.rs, prints the size and alignment of each type here and finds where each variant's data sits (the address of a field minus the address of the value), so the figure is drawn to scale, one cube per byte:

  1. A tag costs a byte, and padding. Option<u8> is 2 bytes: the u8 plus one tag byte saying Some or None. Option<u32> is 8, with the u32 at offset 4: a u32 must start at a multiple of 4, so the tag byte is followed by 3 bytes of padding.
  2. Option<u64>: 16 bytes for 8 of data. The u64 sits at offset 8 and is aligned to 8, so one tag byte costs 8 bytes in all. Every value of a u64 is a valid number, so the tag has nowhere else to go.
  3. Option<&u64>: no tag at all. 8 bytes, the same as &u64, and the same for Box. A reference is never null, so the all-zero pattern is free to mean None: the "null pointer optimisation", which the Option documentation guarantees for references, Box, function pointers and NonZero numbers. A bit pattern a type can never hold is called a niche. Safety without null costs nothing here.
  4. A String is three words. 24 bytes: a capacity, a pointer to the text on the heap, and a length. Taking a String of capacity 16 holding "timeout" apart word by word found them in that order on this build (the Vec documentation leaves the order unspecified).
  5. Conn: four variants in the same 24 bytes. An enum is as big as its largest variant, here Failed's String at offset 0. The others reuse the same bytes: Connecting's attempt and Connected's session_id both sit at offset 8; Idle has no data. size_of::<Conn>() printed 24: not one byte more than the String.
  6. The tag hides in the first word. For Failed the first word is the String's capacity (0x0000000000000010, that is 16). For the other three it held 0x8000000000000000, ...01 and ...02: 263 and up, more than isize::MAX, and a capacity can never be that large (a Vec "panics if the new capacity exceeds isize::MAX bytes", and String::as_mut_vec exposes the Vec<u8> under a String). The compiler stored the tag in that niche.
  7. Option<Conn>: still 24. There are many unused capacities, so None::<Conn> simply takes the next one, 0x8000000000000003. Wrapping an enum in Option cost nothing either.

Recorded with rustc 1.94.0 on Linux x86-64 (the rest of the page used rustc 1.99.0 on the M1 Pro; the three sizes both runs print agree). Where the compiler puts a tag is not a stable guarantee, except the null pointer case: read size_of, do not rely on the layout. The heap buffer in steps 4 to 6 is drawn smaller than scale.

The program, layout.rs, and its output
layout.rs
// What an enum costs in memory: sizes, alignments and where each variant's data sits.
// Offsets are measured with plain references (field address minus value address): no unsafe.
use std::mem::{align_of, size_of};

#[allow(dead_code)]
#[derive(Debug)]
enum Conn {
    Idle,
    Connecting { attempt: u32 },
    Connected { session_id: u64 },
    Failed { error: String },
}

fn off<T, F>(base: &T, field: &F) -> usize {
    field as *const F as usize - base as *const T as usize
}

fn main() {
    // the tag: Option<u8> adds one byte; a wider payload pads the tag up to its alignment
    for (name, s, a) in [
        ("u8", size_of::<u8>(), align_of::<u8>()),
        ("Option<u8>", size_of::<Option<u8>>(), align_of::<Option<u8>>()),
        ("u32", size_of::<u32>(), align_of::<u32>()),
        ("Option<u32>", size_of::<Option<u32>>(), align_of::<Option<u32>>()),
        ("u64", size_of::<u64>(), align_of::<u64>()),
        ("Option<u64>", size_of::<Option<u64>>(), align_of::<Option<u64>>()),
        ("&u64", size_of::<&u64>(), align_of::<&u64>()),
        ("Option<&u64>", size_of::<Option<&u64>>(), align_of::<Option<&u64>>()),
        ("Box<u64>", size_of::<Box<u64>>(), align_of::<Box<u64>>()),
        ("Option<Box<u64>>", size_of::<Option<Box<u64>>>(), align_of::<Option<Box<u64>>>()),
        ("String", size_of::<String>(), align_of::<String>()),
        ("Option<String>", size_of::<Option<String>>(), align_of::<Option<String>>()),
        ("Conn", size_of::<Conn>(), align_of::<Conn>()),
        ("Option<Conn>", size_of::<Option<Conn>>(), align_of::<Option<Conn>>()),
    ] {
        println!("{name:<18} size {s:>2}  align {a}");
    }
    let x = Some(7u64);
    if let Some(v) = &x { println!("Option<u64>: Some's u64 at offset {}", off(&x, v)); }
    let x = Some(7u32);
    if let Some(v) = &x { println!("Option<u32>: Some's u32 at offset {}", off(&x, v)); }
    let c = Conn::Connecting { attempt: 1 };
    if let Conn::Connecting { attempt } = &c { println!("Conn::Connecting: attempt (u32) at offset {}", off(&c, attempt)); }
    let c = Conn::Connected { session_id: 42 };
    if let Conn::Connected { session_id } = &c { println!("Conn::Connected: session_id (u64) at offset {}", off(&c, session_id)); }
    let c = Conn::Failed { error: "timeout".into() };
    if let Conn::Failed { error } = &c { println!("Conn::Failed: error (String, {} bytes) at offset {}", size_of::<String>(), off(&c, error)); }
    // Where is the tag? Read the String's three words, then the first word of each Conn value.
    // A probe, not production code: it reads only words every variant has initialised.
    let mut s = String::with_capacity(16);
    s.push_str("timeout");
    let (cap, len) = (s.capacity(), s.len());
    let w: [usize; 3] = unsafe { std::mem::transmute(s) };
    let names: Vec<&str> = w.iter().map(|&x| if x == cap && x == len { "cap=len" } else if x == cap { "capacity" } else if x == len { "length" } else { "pointer" }).collect();
    println!("String \"timeout\" (capacity {cap}, length {len}) as three words: {:?}", names);
    let _ = unsafe { std::mem::transmute::<[usize; 3], String>(w) };
    let mut e = String::with_capacity(16);
    e.push_str("timeout");
    let first = |c: &Conn| unsafe { *(c as *const Conn as *const usize) };
    for c in [Conn::Idle, Conn::Connecting { attempt: 1 }, Conn::Connected { session_id: 42 }, Conn::Failed { error: e }] {
        println!("first word of {:<40} {:#018x}", format!("{c:?}"), first(&c));
    }
    let none: Option<Conn> = None;
    println!("first word of {:<40} {:#018x}", "None::<Conn>", unsafe { *(&none as *const Option<Conn> as *const usize) });
}
$ rustc --version && uname -sm && rustc --edition 2024 layout.rs && ./layout
rustc 1.94.0 (4a4ef493e 2026-03-02)
Linux x86_64
u8                 size  1  align 1
Option<u8>         size  2  align 1
u32                size  4  align 4
Option<u32>        size  8  align 4
u64                size  8  align 8
Option<u64>        size 16  align 8
&u64               size  8  align 8
Option<&u64>       size  8  align 8
Box<u64>           size  8  align 8
Option<Box<u64>>   size  8  align 8
String             size 24  align 8
Option<String>     size 24  align 8
Conn               size 24  align 8
Option<Conn>       size 24  align 8
Option<u64>: Some's u64 at offset 8
Option<u32>: Some's u32 at offset 4
show the remaining 9 lines
Conn::Connecting: attempt (u32) at offset 8
Conn::Connected: session_id (u64) at offset 8
Conn::Failed: error (String, 24 bytes) at offset 0
String "timeout" (capacity 16, length 7) as three words: ["capacity", "pointer", "length"]
first word of Idle                                     0x8000000000000000
first word of Connecting { attempt: 1 }                0x8000000000000001
first word of Connected { session_id: 42 }             0x8000000000000002
first word of Failed { error: "timeout" }              0x0000000000000010
first word of None::<Conn>                             0x8000000000000003

The syntax, on a chat message

enums.rs
#[derive(Debug, Clone, PartialEq)]
struct Usage {
    user: String,
    tokens: u64,
}

// An enum's variants can carry different data: a "tagged union".
#[derive(Debug)]
enum Message {
    Text { user: String, text: String },
    ToolCall { name: String, args: Vec<String> },
    Image { width: u32, height: u32 },
    Ping,
}

impl Message {
    fn describe(&self) -> String {
        match self {
            Message::Text { user, text } if text.is_empty() => format!("{user} sent nothing"),
            Message::Text { user, text } => format!("{user}: {} chars", text.len()),
            Message::ToolCall { name, args } => format!("call {name} with {} args", args.len()),
            Message::Image { width, height } => format!("image {width}x{height}"),
            Message::Ping => "ping".to_string(),
        }
    }
}

fn main() {
    let u = Usage { user: "u0029".into(), tokens: 9491 };
    let v = Usage { tokens: 10, ..u.clone() }; // struct update syntax
    println!("{u:?}\n{v:?} equal? {}", u == v);
    let msgs = vec![
        Message::Text { user: "ada".into(), text: "hi there".into() },
        Message::Text { user: "bob".into(), text: String::new() },
        Message::ToolCall { name: "search".into(), args: vec!["rust".into()] },
        Message::Image { width: 640, height: 480 },
        Message::Ping,
    ];
    for m in &msgs {
        println!("{}", m.describe());
    }
    println!("{:#?}", msgs[2]);
    let n = 7;
    let kind = match n {
        0 => "zero",
        1..=9 => "one digit",
        _ => "more", // `_` matches anything else
    };
    println!("{n} is {kind}");
    if let Message::Image { width, .. } = &msgs[3] {
        println!("if let: width {width}");
    }
}
$ rustc --edition 2024 enums.rs && ./enums
Usage { user: "u0029", tokens: 9491 }
Usage { user: "u0029", tokens: 10 } equal? false
ada: 8 chars
bob sent nothing
call search with 1 args
image 640x480
ping
ToolCall {
    name: "search",
    args: [
        "rust",
    ],
}
7 is one digit
if let: width 640
  • #[derive(Debug, Clone, PartialEq)] asks the compiler to write the code for printing with {:?}, cloning and ==, as @dataclass writes __repr__ and __eq__.
  • impl Message { ... } holds the methods. &self is a borrowed self; &mut self may change it; plain self consumes it.
  • Patterns can destructure fields, add guards (if text.is_empty()), match ranges (1..=9) and use _ for "anything else". if let handles one variant and ignores the rest.

Forget a variant and the program does not compile. Add a Tool role a year from now, and the compiler lists every match that must learn about it:

$ rustc --edition 2024 match_err.rs
error[E0004]: non-exhaustive patterns: `Role::Tool` not covered
 --> match_err.rs:4:11
  |
4 |     match r {
  |           ^ pattern `Role::Tool` not covered
  |
note: `Role` defined here
 --> match_err.rs:1:6
  |
1 | enum Role { User, Assistant, Tool }
  |      ^^^^                    ---- not covered
  = note: the matched value is of type `Role`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
  |
6 ~         Role::Assistant => "assistant",
7 ~         Role::Tool => todo!(),
  |

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0004`.
[exit code 1]
SolvesWhole classes of "this field should not be None here" bugs; adding a case shows every place to update.
CostsAn enum is as big as its largest variant (box a huge rarely used one); exhaustive matching makes public enums hard to extend without breaking users (#[non_exhaustive] exists for that).
Python todayThe same idea is available as a union of dataclasses plus match and a type checker's exhaustiveness check (assert_never; Python's type checkers are on Python: typing, uv, packaging and the toolchain); Rust enforces it always.

Where an error goes: ? returns it one level up, and the rest of the function never runs

Lines 22 to 43 of code/lang/errors.rs (the whole file is in the closed block under the steps); the highlighted lines are the ones running at each step.

3. Option, Result and ?: errors as values

Rust has no None that can appear anywhere and no exceptions for expected failures. Two enums from the standard library carry them, written like any other enum:

  • Option<T> is Some(value) or None: maybe missing. dict.get, str.find and "first element" return one.
  • Result<T, E> is Ok(value) or Err(error): may fail. Parsing, I/O and network calls return one.

You cannot use the value inside without deciding what happens in the other case. The ? operator is the common decision: "if this is an Err, return it from my function now; otherwise give me the value". It is the explicit, typed version of letting an exception propagate. The recorded program on its three configurations (pick one on the figure):

  1. The call. main calls budget(&bad); bad has context = "8k".
  2. Into get_num. budget calls get_num(cfg, "context").
  3. The key is there. cfg.get("context") is Some("8k"); ok_or makes it Ok("8k"); ? unwraps it, so raw = "8k".
  4. The parse fails. "8k".parse::<u32>() returns Err(ParseIntError { kind: InvalidDigit }).
  5. The error is wrapped. map_err wraps it as Err(BadNumber { key: "context", source }). With no semicolon, that is get_num's return value.
  6. ? returns early. Back in budget, ? sees an Err and returns it from budget at once. Lines 31 and 32 never run: max_output is never read.
  7. main reports it. main's match takes the Err arm and prints error: context is not a number: invalid digit found in string (the message is ConfigError's Display).
The whole program, errors.rs (the error type and main)
errors.rs
use std::collections::HashMap;
use std::fmt;
use std::num::ParseIntError;

#[derive(Debug)]
enum ConfigError {
    Missing(&'static str),
    BadNumber { key: &'static str, source: ParseIntError },
}

impl fmt::Display for ConfigError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            ConfigError::Missing(k) => write!(f, "missing key {k}"),
            ConfigError::BadNumber { key, source } => write!(f, "{key} is not a number: {source}"),
        }
    }
}

impl std::error::Error for ConfigError {}

fn get_num(cfg: &HashMap<&str, &str>, key: &'static str) -> Result<u32, ConfigError> {
    let raw = cfg.get(key).ok_or(ConfigError::Missing(key))?; // Option -> Result, then ?
    raw.trim()
        .parse::<u32>()
        .map_err(|e| ConfigError::BadNumber { key, source: e })
}

fn budget(cfg: &HashMap<&str, &str>) -> Result<u32, ConfigError> {
    let ctx = get_num(cfg, "context")?; // ? returns the error to our caller
    let out = get_num(cfg, "max_output")?;
    Ok(ctx - out)
}

fn main() {
    let good = HashMap::from([("context", "8192"), ("max_output", " 1024")]);
    let bad = HashMap::from([("context", "8k"), ("max_output", "1024")]);
    let missing = HashMap::from([("context", "8192")]);
    for cfg in [&good, &bad, &missing] {
        match budget(cfg) {
            Ok(n) => println!("ok: {n} tokens for the prompt"),
            Err(e) => println!("error: {e}   (debug: {e:?})"),
        }
    }
    let first: Option<&str> = "".split_whitespace().next();
    println!("first word of \"\": {:?}, or default: {}", first, first.unwrap_or("<none>"));
    let n: Result<u8, _> = "300".parse::<u8>();
    println!("\"300\".parse::<u8>() = {n:?}");
    let x: u32 = "12".parse().unwrap(); // fine
    println!("unwrap ok: {x}");
    let y: u32 = "twelve".parse().expect("config value must be a number"); // panics
    println!("{y}");
}
$ rustc --edition 2024 errors.rs && ./errors
ok: 7168 tokens for the prompt
error: context is not a number: invalid digit found in string   (debug: BadNumber { key: "context", source: ParseIntError { kind: InvalidDigit } })
error: missing key max_output   (debug: Missing("max_output"))
first word of "": None, or default: <none>
"300".parse::<u8>() = Err(ParseIntError { kind: PosOverflow })
unwrap ok: 12

thread 'main' (16490500) panicked at errors.rs:51:35:
config value must be a number: ParseIntError { kind: InvalidDigit }
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
[exit code 101]
  • ok_or turns an Option into a Result; map_err converts one error type into another; unwrap_or supplies a default.
  • unwrap() and expect("why") say "this cannot fail; if it does, it is a bug": they panic, as the last line shows. Fine in tests and prototypes; in libraries prefer returning the error.
  • A custom error type is an enum with a Display implementation (the message) and the Error trait (ConfigError above). That is boilerplate, which is why two crates are everywhere (below).

? only works in a function that returns Result or Option, which catches people in main: E0277, "the ? operator can only be used in a function that returns Result or Option", and the compiler proposes the fix, fn main() -> Result<(), Box<dyn std::error::Error>> plus Ok(()) at the end.

The full error
$ rustc --edition 2024 qmark_err.rs
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)
 --> qmark_err.rs:2:30
  |
1 | fn main() {
  | --------- this function should return `Result` or `Option` to accept `?`
2 |     let n: u32 = "42".parse()?;
  |                              ^ cannot use the `?` operator in a function that returns `()`
  |
help: consider adding return type
  |
1 ~ fn main() -> Result<(), Box<dyn std::error::Error>> {
2 |     let n: u32 = "42".parse()?;
3 |     println!("{n}");
4 +     Ok(())
  |

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0277`.
[exit code 1]
Predict: try / except around int(). Which Rust version prints what the Python prints?
d06.py
try:
    n = int("12a")
except ValueError:
    n = 0
print(n)
$ python3.14 d06.py
0
A
d06_a.rs
fn main() {
    let n: i32 = "12a".parse().unwrap_or(0);
    println!("{n}");
}
B
d06_b.rs
fn main() {
    let n: i32 = "12a".parse().unwrap();
    println!("{n}");
}
C
d06_c.rs
fn main() {
    let n: i32 = "12a".parse()?;
    println!("{n}");
}
What the three really did (rustc 1.99.0, debug builds)
A: compiles and runs, matches Python. parse returns a Result; unwrap_or(0) is the except branch.
$ rustc --edition 2024 d06_a.rs && ./d06_a
0
B: compiles, panics at run time, differs. unwrap on an Err panics: Rust's uncaught exception, but you cannot catch it as routine control flow.
$ rustc --edition 2024 d06_b.rs && ./d06_b

thread 'main' (16605353) panicked at d06_b.rs:2:32:
called `Result::unwrap()` on an `Err` value: ParseIntError { kind: InvalidDigit }
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
[exit code 101]
C: refused by the compiler, differs. ? needs the function to return a Result or Option; main returns (): E0277.
$ rustc --edition 2024 d06_c.rs && ./d06_c
error[E0277]: the `?` operator can only be used in a function that returns `Result` or `Option` (or another type that implements `FromResidual`)
 --> d06_c.rs:2:31
  |
1 | fn main() {
  | --------- this function should return `Result` or `Option` to accept `?`
2 |     let n: i32 = "12a".parse()?;
  |                               ^ cannot use the `?` operator in a function that returns `()`
  |
help: consider adding return type
  |
1 ~ fn main() -> Result<(), Box<dyn std::error::Error>> {
2 |     let n: i32 = "12a".parse()?;
3 |     println!("{n}");
4 +     Ok(())
  |

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0277`.
[exit code 1]
Predict: A default argument. Which Rust version prints what the Python prints?
d05.py
def greet(name=None):
    return f"hi {name or 'there'}"

print(greet(), "/", greet("ada"))
$ python3.14 d05.py
hi there / hi ada
A
d05_a.rs
fn greet(name: &str = "there") -> String {
    format!("hi {name}")
}

fn main() {
    println!("{} / {}", greet(), greet("ada"));
}
B
d05_b.rs
fn greet(name: Option<&str>) -> String {
    format!("hi {}", name.unwrap())
}

fn main() {
    println!("{} / {}", greet(None), greet(Some("ada")));
}
C
d05_c.rs
fn greet(name: Option<&str>) -> String {
    format!("hi {}", name.unwrap_or("there"))
}

fn main() {
    println!("{} / {}", greet(None), greet(Some("ada")));
}
What the three really did (rustc 1.99.0, debug builds)
A: refused by the compiler, differs. Rust has no default parameter values: a syntax error, then E0061 for the call with no argument.
$ rustc --edition 2024 d05_a.rs && ./d05_a
error: parameter defaults are not supported
 --> d05_a.rs:1:21
  |
1 | fn greet(name: &str = "there") -> String {
  |                     ^^^^^^^^^

error[E0061]: this function takes 1 argument but 0 arguments were supplied
 --> d05_a.rs:6:25
  |
6 |     println!("{} / {}", greet(), greet("ada"));
  |                         ^^^^^-- argument #1 of type `&str` is missing
  |
note: function defined here
 --> d05_a.rs:1:4
  |
1 | fn greet(name: &str = "there") -> String {
  |    ^^^^^ --------------------
help: provide the argument
show the remaining 8 lines
  |
6 |     println!("{} / {}", greet(/* &str */), greet("ada"));
  |                               ++++++++++

error: aborting due to 2 previous errors

For more information about this error, try `rustc --explain E0061`.
[exit code 1]
B: compiles, panics at run time, differs. Compiles, then panics on greet(None): unwrap on None.
$ rustc --edition 2024 d05_b.rs && ./d05_b

thread 'main' (16605100) panicked at d05_b.rs:2:27:
called `Option::unwrap()` on a `None` value
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
[exit code 101]
C: compiles and runs, matches Python. Option<&str> plus unwrap_or is the direct translation (a builder or two functions are the other usual answers).
$ rustc --edition 2024 d05_c.rs && ./d05_c
hi there / hi ada

thiserror and anyhow

The common split (thiserror, anyhow): libraries define typed error enums so callers can match on them, and thiserror writes the Display and Error code from attributes; applications mostly report errors, and anyhow::Result holds any error plus a chain of context messages. Versions used here: thiserror 2.0.21, anyhow 1.0.104.

main.rs
// A library-style typed error (thiserror) under an application-style error (anyhow).
use anyhow::{Context, Result};
use thiserror::Error;

#[derive(Debug, Error)]
enum ParseError {
    #[error("line {line}: missing field {field}")]
    MissingField { line: usize, field: &'static str },
    #[error("line {line}: bad token count")]
    BadCount { line: usize, #[source] source: std::num::ParseIntError },
}

// typed: callers can match on the variant
fn parse_line(line: usize, s: &str) -> Result<(String, u64), ParseError> {
    let mut it = s.split(',');
    let user = it.next().filter(|u| !u.is_empty()).ok_or(ParseError::MissingField { line, field: "user" })?;
    let n = it.next().ok_or(ParseError::MissingField { line, field: "tokens" })?;
    let n = n.trim().parse().map_err(|source| ParseError::BadCount { line, source })?;
    Ok((user.to_string(), n))
}

// application: any error, plus context explaining what we were doing
fn load(path: &str) -> Result<u64> {
    let text = std::fs::read_to_string(path).with_context(|| format!("reading {path}"))?;
    let mut total = 0;
    for (i, l) in text.lines().enumerate() {
        let (_, n) = parse_line(i + 1, l).context("parsing usage file")?;
        total += n;
    }
    Ok(total)
}

fn main() {
    std::fs::write("good.csv", "ada,10\nbob,32\n").unwrap();
    std::fs::write("bad.csv", "ada,10\nbob,thirty\n").unwrap();
    for p in ["good.csv", "bad.csv", "nope.csv"] {
        match load(p) {
            Ok(t) => println!("{p}: total {t}"),
            Err(e) => println!("{p}: error: {e:#}"), // {:#} prints the whole chain
        }
    }
    match parse_line(7, ",5") {
        Err(ParseError::MissingField { field, .. }) => println!("caller matched: missing {field}"),
        other => println!("{other:?}"),
    }
}
$ cargo run -q
good.csv: total 42
bad.csv: error: parsing usage file: line 2: bad token count: invalid digit found in string
nope.csv: error: reading nope.csv: No such file or directory (os error 2)
caller matched: missing user

The second line is what a user wants to read: what the program was doing (parsing usage file), where (line 2), and the root cause, all from {:#} on the chain. The CLI and the service on Rust: async with tokio, services with axum, and CLIs use this pattern, and a PyO3 extension turns these errors into Python exceptions (Rust: speeding up Python with PyO3 and maturin).

SolvesEvery failure is visible in the signature; nothing is thrown past a caller that did not expect it.
CostsMore words than try/except at the top, and error types to design; ? keeps the middle short.
Common mistakeunwrap() everywhere in library code; or one giant error enum for a whole crate. Prefer one enum per module boundary (error design as a craft: Code design).

4. Traits and generics: duck typing, checked

A trait names a set of methods a type promises to provide, like a Python Protocol, except that a type must say so explicitly (impl Tokenizer for Whitespace) and the compiler checks it before the program runs. A trait may have default methods written in terms of the others. A generic function takes a type parameter with a bound: fn total<T: Tokenizer> accepts any T that implements Tokenizer.

traits.rs
use std::fmt::Display;

// A trait: a named set of methods a type promises to have (like a Protocol).
trait Tokenizer {
    fn name(&self) -> String;
    fn count(&self, text: &str) -> usize;
    // a default method, written once in terms of the others
    fn report(&self, text: &str) -> String {
        format!("{} -> {} tokens", self.name(), self.count(text))
    }
}

struct Whitespace;
struct Chars { per_token: usize }

impl Tokenizer for Whitespace {
    fn name(&self) -> String { "whitespace".into() }
    fn count(&self, text: &str) -> usize { text.split_whitespace().count() }
}

impl Tokenizer for Chars {
    fn name(&self) -> String { format!("chars/{}", self.per_token) }
    fn count(&self, text: &str) -> usize { text.chars().count().div_ceil(self.per_token) }
}

// Generic: one copy of this function is compiled per concrete T (monomorphisation).
fn total<T: Tokenizer>(t: &T, docs: &[&str]) -> usize {
    docs.iter().map(|d| t.count(d)).sum()
}

// Trait object: one compiled copy; the call goes through a table of function pointers.
fn total_dyn(t: &dyn Tokenizer, docs: &[&str]) -> usize {
    docs.iter().map(|d| t.count(d)).sum()
}

// impl Trait in argument position is shorthand for a generic
fn show_all(items: &[impl Display]) -> String {
    items.iter().map(|x| x.to_string()).collect::<Vec<_>>().join(", ")
}

fn main() {
    let docs = ["the cat sat", "on the mat today"];
    println!("{}", Whitespace.report(docs[0]));
    println!("{}", Chars { per_token: 4 }.report(docs[0]));
    println!("generic: {} {}", total(&Whitespace, &docs), total(&Chars { per_token: 4 }, &docs));
    let toks: Vec<Box<dyn Tokenizer>> = vec![Box::new(Whitespace), Box::new(Chars { per_token: 3 })];
    for t in &toks {
        println!("dyn: {} = {}", t.name(), total_dyn(t.as_ref(), &docs));
    }
    println!("{}", show_all(&[1.5, 2.25]));
    println!("size_of &Whitespace = {}, &dyn Tokenizer = {}",
        std::mem::size_of::<&Whitespace>(), std::mem::size_of::<&dyn Tokenizer>());
}
$ rustc --edition 2024 traits.rs && ./traits
whitespace -> 3 tokens
chars/4 -> 3 tokens
generic: 7 7
dyn: whitespace = 7
dyn: chars/3 = 10
1.5, 2.25
size_of &Whitespace = 8, &dyn Tokenizer = 16

There are two ways to call through a trait, and the choice is a real trade-off. The figure follows both through the compiled program:

  1. One generic, written once. mono.rs defines biggest<T: PartialOrd + Copy> once and calls it on slices of u8, i64, f64 and char.
  2. Compiled four times. The release binary's symbol table (nm, recorded below) holds four functions: biggest::<char>, <f64>, <i64> and <u8>. Each is compiled for its own type, so x > b is one machine comparison of that type: this is monomorphisation.
  3. A generic call is direct. biggest(&[1u8, 7, 3]) jumps straight to biggest::<u8>: the target is known when compiling, so it can be inlined and optimised with the caller.
  4. A trait object is a fat pointer. &Whitespace is 8 bytes; &dyn Tokenizer is 16 (recorded above): one word points at the value, the second at the vtable of the value's type.
  5. One vtable per type. The compiler builds one table per type used as dyn Tokenizer: drop, size, align, then name → Chars::name, count → Chars::count, report → the default method. Every &dyn Tokenizer to a Chars shares it; Whitespace has its own.
  6. The call: a load and a jump. total_dyn is compiled once. Each t.count(d) loads the address of count from the table the second word points at, then calls it with the first word as self. The target is not known when compiling, so it cannot be inlined.
  7. The extra word is in the reference, not the value. A value is passed either by a plain reference (8 bytes, like &Whitespace: direct calls) or as &dyn Tokenizer (16 bytes: calls through the table); the value itself carries no table pointer, so you pay only where you write dyn. C++ puts its vtable pointer inside every object of a class with a virtual function instead (8 bytes grow to 16 on C++: classes, templates and the standard library, whose section 2 follows a virtual call through memory; the table and the loads are the same idea).
  8. What the table costs in a hot loop. The same closure called through a generic took 0.289 ns per element, through &dyn Fn 0.954 ns: about three times slower, because the call through the table blocks inlining (section 5 has the full measurement).

Byte rows drawn to scale (one cube per byte) from size_of in traits.rs; the symbol names are mono.rs's recorded nm output; the nanoseconds are iterbench.rs's. The vtable's contents are simplified, and functions are drawn as boxes, not to scale.

Generic <T: Tokenizer>Trait object &dyn Tokenizer
How it is compiledmonomorphisation: one copy of the function per concrete type, each optimised (inlined) for that typeone copy; each call looks the method up in a table of function pointers (a vtable)
Costscompile time and binary size grow with each type usedan indirect call per method; no inlining across it
Use whenthe type is known at compile time (most code)you need a mixed collection (Vec<Box<dyn Tokenizer>>) or a plug-in boundary

Monomorphisation is visible in the compiled program: one generic function used with four types becomes four functions in the symbol table (biggest called on u8, i64, f64 and char slices, release build, symbols listed with nm).

$ rustc --edition 2024 -O mono.rs && ./mono && nm mono | c++filt | grep biggest | cut -c 18- | sort
7 3 1.5 z
2
t mono::biggest::<char>
t mono::biggest::<f64>
t mono::biggest::<i64>
t mono::biggest::<u8>
t mono::biggest_dyn
The program, mono.rs
mono.rs
// Count how many machine-code copies a generic function gets.
#[inline(never)]
fn biggest<T: PartialOrd + Copy>(xs: &[T]) -> T {
    let mut b = xs[0];
    for &x in xs { if x > b { b = x; } }
    b
}

#[inline(never)]
fn biggest_dyn(xs: &[&dyn Fn() -> f64]) -> f64 {
    xs.iter().map(|f| f()).fold(f64::MIN, f64::max)
}

fn main() {
    use std::hint::black_box; // hide the inputs so the optimiser cannot precompute the answers
    println!("{} {} {} {}", biggest(black_box(&[1u8, 7, 3])), biggest(black_box(&[1i64, -7, 3])),
        biggest(black_box(&[1.5f64, 0.5])), biggest(black_box(&['a', 'z'])));
    let one = || 1.0; let two = || 2.0;
    println!("{}", biggest_dyn(&[&one, &two]));
}

Section 5 measures what the vtable costs in a hot loop. Two real errors worth recognising. Use an operator the bound does not promise, and you get E0369, "binary operation > cannot be applied to type &T", with the help "consider restricting type parameter T with trait PartialOrd". Pass a type that does not implement the trait, and you get E0277, "the trait bound Whitespace: Tokenizer is not satisfied", pointing at the call and at the bound; Python would fail at run time, on the first call to the missing method.

The two errors in full
$ rustc --edition 2024 bound_err.rs
error[E0369]: binary operation `>` cannot be applied to type `&T`
 --> bound_err.rs:4:14
  |
4 |         if x > best {
  |            - ^ ---- &T
  |            |
  |            &T
  |
help: consider restricting type parameter `T` with trait `PartialOrd`
  |
1 | fn largest<T: std::cmp::PartialOrd>(items: &[T]) -> &T {
  |             ++++++++++++++++++++++

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0369`.
[exit code 1]
$ rustc --edition 2024 notimpl_err.rs
error[E0277]: the trait bound `Whitespace: Tokenizer` is not satisfied
  --> notimpl_err.rs:12:26
   |
12 |     println!("{}", total(&Whitespace, &["a b"]));
   |                    ----- ^^^^^^^^^^^ unsatisfied trait bound
   |                    |
   |                    required by a bound introduced by this call
   |
help: the trait `Tokenizer` is not implemented for `Whitespace`
  --> notimpl_err.rs:5:1
   |
 5 | struct Whitespace;
   | ^^^^^^^^^^^^^^^^^
help: this trait has no implementations, consider adding one
  --> notimpl_err.rs:1:1
   |
 1 | trait Tokenizer {
   | ^^^^^^^^^^^^^^^
show the remaining 10 lines
note: required by a bound in `total`
  --> notimpl_err.rs:7:13
   |
 7 | fn total<T: Tokenizer>(t: &T, docs: &[&str]) -> usize {
   |             ^^^^^^^^^ required by this bound in `total`

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0277`.
[exit code 1]
  • No inheritance. Share behaviour with default methods and generic functions, and share data by putting one struct inside another. Python programmers rarely miss class hierarchies after a week.
  • The standard traits matter: Debug, Clone, Copy, PartialEq, Eq, Hash, Ord, Default, Display, From/Into, Iterator. Most are derivable; implementing Display is Rust's __str__, Add its __add__ (Python's side of these hooks: Python: the data model and protocols). A missing standard trait is a common surprise, as in the prompt below: floats are not Ord.
  • The orphan rule: you may implement a trait for a type only if your crate defines the trait or the type. To add a foreign trait to a foreign type, wrap the type in a one-field struct of your own (the "newtype" pattern).
Predict: Sort floats. Which Rust version prints what the Python prints?
d11.py
print(sorted([0.3, 0.1, 0.2]))
$ python3.14 d11.py
[0.1, 0.2, 0.3]
A
d11_a.rs
fn main() {
    let mut v = vec![0.3, 0.1, 0.2];
    v.sort();
    println!("{v:?}");
}
B
d11_b.rs
fn main() {
    let mut v = vec![0.3, 0.1, 0.2];
    v.sort_by(|a, b| b.total_cmp(a));
    println!("{v:?}");
}
C
d11_c.rs
fn main() {
    let mut v: Vec<f64> = vec![0.3, 0.1, 0.2];
    v.sort_by(|a, b| a.partial_cmp(b).unwrap());
    println!("{v:?}");
}
What the three really did (rustc 1.99.0, debug builds)
A: refused by the compiler, differs. f64 is not Ord (NaN is not comparable), so sort is refused: E0277.
$ rustc --edition 2024 d11_a.rs && ./d11_a
error[E0277]: the trait bound `{float}: Ord` is not satisfied
 --> d11_a.rs:3:7
  |
3 |     v.sort();
  |       ^^^^ the trait `Ord` is not implemented for `{float}`
  |
  = help: the following other types implement trait `Ord`:
            i128
            i16
            i32
            i64
            i8
            isize
            u128
            u16
          and 4 others
note: required by a bound in `slice::<impl [T]>::sort`
 --> /rustc/b940084d7eb6a299eb4bfeb8e34901bc051e7ac4/library/alloc/src/slice.rs:131:4
show the remaining 5 lines

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0277`.
[exit code 1]
B: refused by the compiler, differs. Refused before any sorting: the float literals' type is not known yet when total_cmp is looked up (E0599). Annotating Vec<f64> fixes that, and then it would sort descending.
$ rustc --edition 2024 d11_b.rs && ./d11_b
error[E0599]: no method named `total_cmp` found for reference `&{float}` in the current scope
 --> d11_b.rs:3:24
  |
3 |     v.sort_by(|a, b| b.total_cmp(a));
  |                        ^^^^^^^^^
  |
help: there is a method `partial_cmp` with a similar name
  |
3 -     v.sort_by(|a, b| b.total_cmp(a));
3 +     v.sort_by(|a, b| b.partial_cmp(a));
  |

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0599`.
[exit code 1]
C: compiles and runs, matches Python. partial_cmp plus unwrap sorts ascending (and panics if a NaN appears; total_cmp orders NaN instead).
$ rustc --edition 2024 d11_c.rs && ./d11_c
[0.1, 0.2, 0.3]

5. Iterators and closures: lazy pipelines that cost nothing

An iterator in Rust is any type with a next() method returning Option<Item>, the same protocol as Python's __next__ raising StopIteration. Adapters such as map, filter, zip, enumerate, take build a lazy pipeline, like a generator expression; a consumer (collect, sum, count, fold, a for loop) runs it. A closure is an anonymous function that can capture variables from where it is written: |x| x * 2 is Python's lambda x: x * 2, but with any number of statements.

What is new for a Python programmer is the cost, so it comes first. Rust's claim is that the iterator chain compiles to the same machine code as the hand-written loop. The same work five ways (sum of x*x over the even values in 10 million u64, release build, best of 9) and in CPython 3.14 (best of 3):

The benchmark code, the raw recordings and the load average
iterbench.rs (lines 1 to 31)
// Is an iterator chain really as fast as a hand-written loop? Same work, five ways:
// sum of x*x over the even numbers in a Vec<u64> of 10 million pseudo-random values.
use std::hint::black_box;
use std::time::Instant;

#[inline(never)]
fn index_loop(v: &[u64]) -> u64 {
    let mut s = 0u64;
    let mut i = 0;
    while i < v.len() { let x = v[i]; if x % 2 == 0 { s = s.wrapping_add(x * x); } i += 1; }
    s
}
#[inline(never)]
fn for_loop(v: &[u64]) -> u64 {
    let mut s = 0u64;
    for &x in v { if x % 2 == 0 { s = s.wrapping_add(x * x); } }
    s
}
#[inline(never)]
fn chain(v: &[u64]) -> u64 {
    v.iter().filter(|&&x| x % 2 == 0).map(|&x| x * x).fold(0u64, |a, b| a.wrapping_add(b))
}
#[inline(never)]
fn generic_closure<F: Fn(u64) -> u64>(v: &[u64], f: F) -> u64 {
    v.iter().fold(0u64, |a, &x| a.wrapping_add(f(x)))
}
#[inline(never)]
fn dyn_closure(v: &[u64], f: &dyn Fn(u64) -> u64) -> u64 {
    v.iter().fold(0u64, |a, &x| a.wrapping_add(f(x)))
}
$ rustc --edition 2024 -C opt-level=3 iterbench.rs && ./iterbench
while loop with v[i]           0.290 ns/element  result 1662703719376
for x in v                     0.297 ns/element  result 1662703719376
iter().filter().map().fold()   0.293 ns/element  result 1662703719376
generic closure F: Fn          0.289 ns/element  result 1662703719376
&dyn Fn closure                0.954 ns/element  result 1662703719376
$ python3.14 iterbench.py
for loop                         71.4 ns/element  result 1662703719376
sum(generator)                   45.8 ns/element  result 1662703719376
$ sysctl -n vm.loadavg; sysctl -n machdep.cpu.brand_string
{ 16.52 15.93 12.08 }
Apple M1 Pro
$ sysctl -n vm.loadavg
{ 17.03 16.06 12.18 }

The chain runs as fast as the loop; only a closure hidden behind &dyn Fn is slower, and CPython's generator about 150 times slower than the chain

measured All four statically dispatched versions take the same time, about 0.293 ns per element: the closures were inlined and the loop vectorised, so the chain really is free. Calling the closure through &dyn Fn, with the target hidden from the optimiser, blocks inlining and takes 0.954 ns, about three times slower: still far below CPython's 45.8 ns per element for the generator expression (71.4 for the plain loop). The machine was busy (load average around 16 on 10 cores, recorded before and after), so take the ratios, not the absolute values; all seven results agree (1662703719376).

Why it costs nothing: one value, pulled from the end

The laziness is Python's; what makes it free is how the chain is built. lazy.rs runs the chain from iters.rs with a print inside each closure, then the same work the Python-list way, then with take(2); the figure replays its trace:

  1. Built: one small value, nothing ran. words.iter().filter(..).map(..) is a single value of 16 bytes whose type nests the stages: Map<Filter<Iter<&str>, closure>, closure> (type_name_of_val printed it). The closures are part of the type, so the compiler sees every call; no closure has run yet.
  2. collect pulls "Rust" through. collect asks Map for an item, Map asks Filter, Filter asks the slice iterator. "Rust" comes back: the filter keeps it, the map lowercases it, collect pushes "rust".
  3. "is" stops at the filter. The filter drops it and asks the slice for the next word itself; the map never sees "is".
  4. "fast", then "and". Each word goes all the way through before the next is read: the trace alternates filter, map, filter, map.
  5. "safe", "and", "fun", then the end. The slice runs out, next() returns None, and collect returns the 6 words. No list existed in between: the chain held one word at a time.
  6. The Python-list habit: filter everything first. Collecting after the filter runs it on all 7 words into a first Vec of 6.
  7. Then map, into a second Vec. The map runs 6 times over the first Vec: two full buffers, and the trace reads 7 filters, then 6 maps.
  8. take(2) stops early. With .take(2) before collect, pulling stops once "fast" is out: 3 words filtered, 2 mapped; "and", "safe", "and" and "fun" are never read.
The program, lazy.rs, and its trace
lazy.rs
// The chain from iters.rs, with a print in each closure: who runs, in what order.
// Lazy: collect pulls one word at a time through filter and map.
// Eager: the Python-list habit, a full Vec after each step.
// take(2): the consumer stops early, so the source is never read to the end.
fn main() {
    let words = ["Rust", "is", "fast", "and", "safe", "and", "fun"];
    let chain = words.iter()
        .filter(|w| { let keep = w.len() > 2; println!("  filter {w:<5} {}", if keep { "keep" } else { "drop" }); keep })
        .map(|w| { println!("  map    {w:<5} -> {}", w.to_lowercase()); w.to_lowercase() });
    println!("lazy: chain built, nothing printed yet");
    println!("lazy: the chain is one value of {} bytes, type {}", std::mem::size_of_val(&chain), std::any::type_name_of_val(&chain));
    let long: Vec<String> = chain.collect();
    println!("lazy: collect returned {long:?}");
    let kept: Vec<&&str> = words.iter()
        .filter(|w| { let keep = w.len() > 2; println!("  filter {w:<5} {}", if keep { "keep" } else { "drop" }); keep })
        .collect();
    println!("eager: first Vec, {} items {kept:?}", kept.len());
    let lower: Vec<String> = kept.iter()
        .map(|w| { println!("  map    {w:<5} -> {}", w.to_lowercase()); w.to_lowercase() })
        .collect();
    println!("eager: second Vec, {} items {lower:?}", lower.len());
    // Lazy again, but the consumer wants only two: the rest of the words are never looked at.
    let two: Vec<String> = words.iter()
        .filter(|w| { let keep = w.len() > 2; println!("  filter {w:<5} {}", if keep { "keep" } else { "drop" }); keep })
        .map(|w| { println!("  map    {w:<5} -> {}", w.to_lowercase()); w.to_lowercase() })
        .take(2)
        .collect();
    println!("take(2): collect returned {two:?}");
}
$ rustc --version && uname -sm && rustc --edition 2024 lazy.rs && ./lazy
rustc 1.94.0 (4a4ef493e 2026-03-02)
Linux x86_64
lazy: chain built, nothing printed yet
lazy: the chain is one value of 16 bytes, type core::iter::adapters::map::Map<core::iter::adapters::filter::Filter<core::slice::iter::Iter<'_, &str>, lazy::main::{{closure}}>, lazy::main::{{closure}}>
  filter Rust  keep
  map    Rust  -> rust
  filter is    drop
  filter fast  keep
  map    fast  -> fast
  filter and   keep
  map    and   -> and
  filter safe  keep
  map    safe  -> safe
  filter and   keep
  map    and   -> and
  filter fun   keep
  map    fun   -> fun
lazy: collect returned ["rust", "fast", "and", "safe", "and", "fun"]
show the remaining 21 lines
  filter Rust  keep
  filter is    drop
  filter fast  keep
  filter and   keep
  filter safe  keep
  filter and   keep
  filter fun   keep
eager: first Vec, 6 items ["Rust", "fast", "and", "safe", "and", "fun"]
  map    Rust  -> rust
  map    fast  -> fast
  map    and   -> and
  map    safe  -> safe
  map    and   -> and
  map    fun   -> fun
eager: second Vec, 6 items ["rust", "fast", "and", "safe", "and", "fun"]
  filter Rust  keep
  map    Rust  -> rust
  filter is    drop
  filter fast  keep
  map    fast  -> fast
take(2): collect returned ["rust", "fast"]

The rest of the API, in one recorded program:

iters.rs
fn main() {
    let words = ["Rust", "is", "fast", "and", "safe", "and", "fun"];
    // An iterator chain: lazy until something consumes it (collect, sum, for).
    let long: Vec<String> = words.iter()
        .filter(|w| w.len() > 2)
        .map(|w| w.to_lowercase())
        .collect();
    println!("{long:?}");
    // Laziness, visible: nothing is printed until next() is called.
    let mut it = (1..=3).map(|x| { println!("  computing {x}"); x * 10 });
    println!("built the iterator");
    println!("first = {:?}", it.next());
    // Python's enumerate, zip, sum, any, max_by_key all exist
    for (i, w) in words.iter().enumerate().skip(5) { println!("{i} {w}"); }
    let lens: usize = words.iter().map(|w| w.len()).sum();
    let pairs: Vec<(char, usize)> = "abc".chars().zip(1..).collect();
    println!("lens {lens}, pairs {pairs:?}, any 'fun' {}", words.contains(&"fun"));
    println!("longest {:?}", words.iter().max_by_key(|w| w.len()));
    let (even, odd): (Vec<u32>, Vec<u32>) = (1..=6).partition(|n| n % 2 == 0);
    println!("even {even:?} odd {odd:?}");
    // Closures capture their environment: by reference, by mutable reference, or by value
    let limit = 4;
    let short = |w: &str| w.len() < limit; // borrows limit (Fn)
    let mut seen = 0;
    let mut count = |_w: &str| seen += 1; // mutably borrows seen (FnMut)
    for w in words { count(w); }
    let name = String::from("owner");
    let consume = move || name.len(); // moves name into the closure
    println!("short {}, seen {seen}, consume() {}", words.iter().filter(|w| short(w)).count(), consume());
    // A generator-like iterator: implement next()
    struct Countdown(u32);
    impl Iterator for Countdown {
        type Item = u32;
        fn next(&mut self) -> Option<u32> {
            if self.0 == 0 { None } else { self.0 -= 1; Some(self.0 + 1) }
        }
    }
    println!("{:?}", Countdown(3).collect::<Vec<_>>());
}
Predict, then reveal: Which line comes first: "built the iterator" or "computing 1"? And how many times does "computing" print?
$ rustc --edition 2024 iters.rs && ./iters
["rust", "fast", "and", "safe", "and", "fun"]
built the iterator
  computing 1
first = Some(10)
5 and
6 fun
lens 23, pairs [('a', 1), ('b', 2), ('c', 3)], any 'fun' true
longest Some("safe")
even [2, 4, 6] odd [1, 3, 5]
short 4, seen 7, consume() 5
[3, 2, 1]

Closures capture in the least demanding way that works, and the compiler records which in the closure's type: Fn (reads captured values: short above), FnMut (changes them: count), FnOnce (moves them out, so it can run once). move before a closure makes it take ownership of what it captures (consume), needed when the closure outlives the current function, as a thread's does (Rust: lifetimes, smart pointers, threads and unsafe). A type with a next() method (Countdown) is Rust's generator: any struct can be an iterator.

Predict: A list comprehension. Which Rust version prints what the Python prints?
d07.py
print([x * x for x in range(5) if x % 2 == 0])
$ python3.14 d07.py
[0, 4, 16]
A
d07_a.rs
fn main() {
    let v = (0..5).filter(|x| x % 2 == 0).map(|x| x * x);
    println!("{v:?}");
}
B
d07_b.rs
fn main() {
    let v: Vec<i32> = (0..5).filter(|x| x % 2 == 0).map(|x| x * x).collect();
    println!("{v:?}");
}
C
d07_c.rs
fn main() {
    let v: Vec<i32> = (1..5).filter(|x| x % 2 == 0).map(|x| x * x).collect();
    println!("{v:?}");
}
What the three really did (rustc 1.99.0, debug builds)
A: compiles and runs, differs. Compiles and prints the iterator itself, not its values: adapters are lazy and nothing ran. You need collect.
$ rustc --edition 2024 d07_a.rs && ./d07_a
Map { iter: Filter { iter: 0..5 } }
B: compiles and runs, matches Python. filter, map, collect into a Vec: the comprehension.
$ rustc --edition 2024 d07_b.rs && ./d07_b
[0, 4, 16]
C: compiles and runs, differs. 1..5 starts at 1, so 0 is missing. Ranges are half-open like Python's range, but the start matters.
$ rustc --edition 2024 d07_c.rs && ./d07_c
[4, 16]
Predict: Update a list in place. Which Rust version prints what the Python prints?
d08.py
nums = [1, 2, 3]
for i, x in enumerate(nums):
    nums[i] = x * 10
print(nums)
$ python3.14 d08.py
[10, 20, 30]
A
d08_a.rs
fn main() {
    let mut nums = vec![1, 2, 3];
    for (i, x) in nums.iter().enumerate() {
        nums[i] = x * 10;
    }
    println!("{nums:?}");
}
B
d08_b.rs
fn main() {
    let nums = vec![1, 2, 3];
    for mut x in nums.clone() {
        x *= 10;
    }
    println!("{nums:?}");
}
C
d08_c.rs
fn main() {
    let mut nums = vec![1, 2, 3];
    for x in nums.iter_mut() {
        *x *= 10;
    }
    println!("{nums:?}");
}
What the three really did (rustc 1.99.0, debug builds)
A: refused by the compiler, differs. The loop holds a shared borrow of nums while the body writes to it: E0502.
$ rustc --edition 2024 d08_a.rs && ./d08_a
error[E0502]: cannot borrow `nums` as mutable because it is also borrowed as immutable
 --> d08_a.rs:4:9
  |
3 |       for (i, x) in nums.iter().enumerate() {
  |       -             -----------------------
  |       |             |
  |       |             immutable borrow occurs here
  |  _____|             immutable borrow later used here
  | |
4 | |         nums[i] = x * 10;
  | |         ^^^^ mutable borrow occurs here
5 | |     }
  | |_____- this for loop borrows `nums` immutably, preventing mutation within its body
  |
  = help: consider using an index-based loop instead, or collecting modifications into a separate collection

error: aborting due to 1 previous error

For more information about this error, try `rustc --explain E0502`.
[exit code 1]
B: compiles (with a warning) and runs, differs. Compiles (with a warning), but each x is a copy in a clone; nums is unchanged.
$ rustc --edition 2024 d08_b.rs && ./d08_b
warning: unused variable: `x`
 --> d08_b.rs:3:9
  |
3 |     for mut x in nums.clone() {
  |         ^^^^^ help: if this is intentional, prefix it with an underscore: `_x`
  |
  = note: `#[warn(unused_variables)]` (part of `#[warn(unused)]`) on by default

warning: 1 warning emitted

[1, 2, 3]
C: compiles and runs, matches Python. iter_mut yields &mut i32; *x writes through it.
$ rustc --edition 2024 d08_c.rs && ./d08_c
[10, 20, 30]
Predict: sorted with a key. Which Rust version prints what the Python prints?
d10.py
users = [("cy", 5), ("bob", 9), ("ada", 5)]
print(sorted(users, key=lambda u: (-u[1], u[0])))
$ python3.14 d10.py
[('bob', 9), ('ada', 5), ('cy', 5)]
A
d10_a.rs
fn main() {
    let mut users = vec![("cy", 5), ("bob", 9), ("ada", 5)];
    users.sort();
    println!("{users:?}");
}
B
d10_b.rs
fn main() {
    let mut users = vec![("cy", 5), ("bob", 9), ("ada", 5)];
    users.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
    println!("{users:?}");
}
C
d10_c.rs
fn main() {
    let mut users = vec![("cy".to_string(), 5), ("bob".to_string(), 9), ("ada".to_string(), 5)];
    users.sort_by_key(|u| (-u.1, &u.0));
    println!("{users:?}");
}
What the three really did (rustc 1.99.0, debug builds)
A: compiles and runs, differs. Tuples compare field by field, so this sorts by name: a different order.
$ rustc --edition 2024 d10_a.rs && ./d10_a
[("ada", 5), ("bob", 9), ("cy", 5)]
B: compiles and runs, matches Python. A comparator: count descending (b against a), then name ascending. This is how the root's token counter sorts.
$ rustc --edition 2024 d10_b.rs && ./d10_b
[("bob", 9), ("ada", 5), ("cy", 5)]
C: refused by the compiler, differs. sort_by_key cannot return a key that borrows from the element (&u.0): a lifetime error. sort_by_cached_key with a cloned name, or sort_by, works.
$ rustc --edition 2024 d10_c.rs && ./d10_c
error: lifetime may not live long enough
 --> d10_c.rs:3:27
  |
3 |     users.sort_by_key(|u| (-u.1, &u.0));
  |                        -- ^^^^^^^^^^^^ returning this value requires that `'1` must outlive `'2`
  |                        ||
  |                        |return type of closure is (i32, &'2 String)
  |                        has type `&'1 (String, i32)`

error: aborting due to 1 previous error

[exit code 1]
SolvesReadable pipelines with no speed penalty; laziness means no intermediate lists.
CostsLong chains have long type names in errors; collect sometimes needs a type hint (collect::<Vec<_>>()).
Common mistakeBuilding a chain and never consuming it: nothing runs (clippy warns, and candidate A of the comprehension prompt above prints the unconsumed iterator).

6. Collections

PythonRust (std::collections)Notes
listVec<T>contiguous elements of one type, not pointers to objects; v[i] panics out of range, v.get(i) returns an Option
dictHashMap<K, V>arbitrary iteration order, randomly seeded per process
sorted dict (no built-in)BTreeMap<K, V>kept sorted by key; range queries
setHashSet<T>, BTreeSet<T>union, intersection, difference
collections.dequeVecDeque<T>ring buffer, cheap at both ends
heapqBinaryHeap<T>a max-heap (wrap items in Reverse for a min-heap)

The habit to change first is counting into a dict. Predict before reading on:

Predict: Count words in a dict. Which Rust version prints what the Python prints?
d01.py
text = "the cat and the hat"
counts = {}
for w in text.split():
    counts[w] = counts.get(w, 0) + 1
print(counts["the"], counts["cat"])
$ python3.14 d01.py
2 1
A
d01_a.rs
use std::collections::HashMap;
fn main() {
    let text = "the cat and the hat";
    let mut counts: HashMap<&str, i32> = HashMap::new();
    for w in text.split_whitespace() {
        counts[w] += 1;
    }
    println!("{} {}", counts["the"], counts["cat"]);
}
B
d01_b.rs
use std::collections::HashMap;
fn main() {
    let text = "the cat and the hat";
    let mut counts: HashMap<&str, i32> = HashMap::new();
    for w in text.split_whitespace() {
        counts.insert(w, counts.get(w).unwrap() + 1);
    }
    println!("{} {}", counts["the"], counts["cat"]);
}
C
d01_c.rs
use std::collections::HashMap;
fn main() {
    let text = "the cat and the hat";
    let mut counts: HashMap<&str, i32> = HashMap::new();
    for w in text.split_whitespace() {
        *counts.entry(w).or_insert(0) += 1;
    }
    println!("{} {}", counts["the"], counts["cat"]);
}
What the three really did (rustc 1.99.0, debug builds)
A: refused by the compiler, differs. HashMap implements Index (read) but not IndexMut, so counts[w] += 1 cannot insert or update: E0594.
$ rustc --edition 2024 d01_a.rs && ./d01_a
warning: variable does not need to be mutable
 --> d01_a.rs:4:9
  |
4 |     let mut counts: HashMap<&str, i32> = HashMap::new();
  |         ----^^^^^^
  |         |
  |         help: remove this `mut`
  |
  = note: `#[warn(unused_mut)]` (part of `#[warn(unused)]`) on by default

error[E0594]: cannot assign to data in an index of `HashMap<&str, i32>`
 --> d01_a.rs:6:9
  |
6 |         counts[w] += 1;
  |         ^^^^^^^^^^^^^^ cannot assign
  |
  = help: trait `IndexMut` is required to modify indexed content, but it is not implemented for `HashMap<&str, i32>`
  = help: to modify a `HashMap<&str, i32>`, use `.get_mut()`, `.insert()` or the entry API
show the remaining 5 lines

error: aborting due to 1 previous error; 1 warning emitted

For more information about this error, try `rustc --explain E0594`.
[exit code 1]
B: compiles, panics at run time, differs. Compiles, then panics on the first word: get returns None for a new key and unwrap on None panics.
$ rustc --edition 2024 d01_b.rs && ./d01_b

thread 'main' (16603753) panicked at d01_b.rs:6:40:
called `Option::unwrap()` on a `None` value
note: run with `RUST_BACKTRACE=1` environment variable to display a backtrace
[exit code 101]
C: compiles and runs, matches Python. The entry API: one lookup, insert 0 if absent, then add. This is the idiom for counting.
$ rustc --edition 2024 d01_c.rs && ./d01_c
2 1

The entry API (*counts.entry(w).or_insert(0) += 1) is the idiom for "update or insert" with one lookup; the two tempting alternatives fail as shown. The tour of the other collections, in one program:

colls.rs
use std::collections::{BTreeMap, HashMap, HashSet, VecDeque};

fn main() {
    // Vec: a growable array. Capacity grows by doubling, so push is cheap on average.
    let mut v = Vec::new();
    let mut caps = vec![];
    for i in 0..20 { v.push(i); if caps.last() != Some(&v.capacity()) { caps.push(v.capacity()); } }
    println!("Vec capacities seen while pushing 20 items: {caps:?}");
    println!("v.get(99) = {:?}  (v[99] would panic)", v.get(99));

    // HashMap: the entry API does "get or insert" with one lookup
    let text = "the cat and the hat and the bat";
    let mut counts: HashMap<&str, u32> = HashMap::new();
    for w in text.split(' ') { *counts.entry(w).or_insert(0) += 1; }
    println!("HashMap iteration order: {:?}", counts.iter().collect::<Vec<_>>());
    let mut sorted: Vec<(&str, u32)> = counts.into_iter().collect();
    sorted.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0))); // count desc, then word asc
    println!("sorted: {sorted:?}");

    // BTreeMap: kept sorted by key, so iteration order is deterministic
    let bt: BTreeMap<&str, u32> = text.split(' ').map(|w| (w, w.len() as u32)).collect();
    println!("BTreeMap: {bt:?}");
    println!("range \"b\"..\"d\": {:?}", bt.range("b".."d").collect::<Vec<_>>());

    // HashSet: membership and set algebra
    let a: HashSet<u32> = [1, 2, 3, 4].into();
    let b: HashSet<u32> = [3, 4, 5].into();
    let mut inter: Vec<_> = a.intersection(&b).copied().collect();
    inter.sort();
    println!("intersection {inter:?}, contains 5? {}", a.contains(&5));

    // VecDeque: a ring buffer, O(1) at both ends (Python's collections.deque)
    let mut q: VecDeque<u32> = VecDeque::new();
    q.push_back(1); q.push_back(2); q.push_front(0);
    let front = q.pop_front();
    println!("deque after pop_front: {q:?}, popped {front:?}");
}
$ rustc --edition 2024 colls.rs && ./colls
Vec capacities seen while pushing 20 items: [4, 8, 16, 32]
v.get(99) = None  (v[99] would panic)
HashMap iteration order: [("bat", 1), ("the", 3), ("cat", 1), ("and", 2), ("hat", 1)]
sorted: [("the", 3), ("and", 2), ("bat", 1), ("cat", 1), ("hat", 1)]
BTreeMap: {"and": 3, "bat": 3, "cat": 3, "hat": 3, "the": 3}
range "b".."d": [("bat", 3), ("cat", 3)]
intersection [3, 4], contains 5? false
deque after pop_front: [1, 2], popped Some(0)

The same binary, run three more times. Same input, different order each run:

$ for i in 1 2 3; do ./colls | sed -n 3p; done
HashMap iteration order: [("bat", 1), ("cat", 1), ("the", 3), ("and", 2), ("hat", 1)]
HashMap iteration order: [("hat", 1), ("and", 2), ("the", 3), ("bat", 1), ("cat", 1)]
HashMap iteration order: [("cat", 1), ("the", 3), ("bat", 1), ("and", 2), ("hat", 1)]

Python dicts keep insertion order (guaranteed since 3.7); Rust's HashMap does not, and its default hasher (SipHash 1-3) is randomly seeded so that an attacker who controls the keys cannot force collisions ("HashDoS"), as the HashMap documentation explains. Sort before printing (as the root's token counter does) or use a BTreeMap. For integer keys in a hot loop a faster non-DoS-resistant hasher (the rustc-hash or ahash crates) is a common swap.

Predict: Dictionary order. Which Rust version prints what the Python prints?
d09.py
d = {"b": 1, "a": 2, "c": 3, "e": 4, "d": 5, "f": 6}
print(list(d))
$ python3.14 d09.py
['b', 'a', 'c', 'e', 'd', 'f']
A
d09_a.rs
use std::collections::HashMap;
fn main() {
    let d = HashMap::from([("b", 1), ("a", 2), ("c", 3), ("e", 4), ("d", 5), ("f", 6)]);
    println!("{:?}", d.keys().collect::<Vec<_>>());
}
B
d09_b.rs
use std::collections::BTreeMap;
fn main() {
    let d = BTreeMap::from([("b", 1), ("a", 2), ("c", 3), ("e", 4), ("d", 5), ("f", 6)]);
    println!("{:?}", d.keys().collect::<Vec<_>>());
}
C
d09_c.rs
fn main() {
    let d = vec![("b", 1), ("a", 2), ("c", 3), ("e", 4), ("d", 5), ("f", 6)];
    println!("{:?}", d.iter().map(|(k, _)| k).collect::<Vec<_>>());
}
What the three really did (rustc 1.99.0, debug builds)
A: compiles and runs, differs. HashMap iterates in arbitrary order, and the hasher is randomly seeded per process: the order changed between runs.
$ rustc --edition 2024 d09_a.rs && ./d09_a
["d", "b", "c", "f", "a", "e"]
B: compiles and runs, differs. BTreeMap is ordered by key (alphabetical here), not by insertion.
$ rustc --edition 2024 d09_b.rs && ./d09_b
["a", "b", "c", "d", "e", "f"]
C: compiles and runs, matches Python. Python dicts keep insertion order (guaranteed since 3.7). Rust's standard library has no insertion-ordered map; a Vec of pairs (or the indexmap crate) keeps it.
$ rustc --edition 2024 d09_c.rs && ./d09_c
["b", "a", "c", "e", "d", "f"]
Candidate a, run three more times
$ ./d09_a; ./d09_a; ./d09_a
["b", "c", "a", "d", "e", "f"]
["a", "e", "d", "f", "c", "b"]
["b", "c", "e", "d", "a", "f"]

7. Testing: unit, integration, documentation

Testing is built into the language and cargo, with no framework to install. Where a test lives decides what it can see; the figure shows the three kinds in the root's token counter crate (tokstat, the library-plus-binary layout taught under modules on Rust: the essentials):

  • Unit tests live next to the code in a #[cfg(test)] mod tests (compiled only for cargo test) and may test private functions.
  • Integration tests are files in tests/, compiled as a separate crate, so they see only the public API; they can also run the built binary.
  • Documentation tests: code blocks inside /// doc comments are compiled and run, so the examples in the docs cannot rot.

Three kinds of test, three levels of access

tokstat/ Cargo.toml src/lib.rs pub mod tally; pub mod tokenize; src/main.rs the binary, a thin layer on the library src/tokenize.rs /// ``` assert_eq!(count_tokens("x86_64 is 2 tokens"), 5); ```doc test: run as a user of the crate #[cfg(test)] mod tests { use super::*; ... }unit tests: may call private is_token_byte tests/cli.rsintegration: a separate crate, public API and the built binary
The two test files: src/tokenize.rs (a doc test and two unit tests) and tests/cli.rs (two integration tests)
tokenize.rs (lines 1 to 44)
//! What counts as a token.

/// Number of maximal runs of ASCII letters and digits.
///
/// ```
/// use tokstat::count_tokens;
/// assert_eq!(count_tokens("x86_64 is 2 tokens"), 5);
/// assert_eq!(count_tokens("café"), 1); // 'é' is not ASCII, so it separates
/// ```
pub fn count_tokens(text: &str) -> u64 {
    let mut n = 0;
    let mut inside = false;
    for b in text.bytes() {
        let tok = is_token_byte(b);
        if tok && !inside {
            n += 1;
        }
        inside = tok;
    }
    n
}

// Private: not visible outside this module.
fn is_token_byte(b: u8) -> bool {
    b.is_ascii_alphanumeric()
}

#[cfg(test)]
mod tests {
    use super::*; // unit tests may see private items

    #[test]
    fn private_helper() {
        assert!(is_token_byte(b'a'));
        assert!(!is_token_byte(b'_'));
    }

    #[test]
    fn edge_cases() {
        assert_eq!(count_tokens(""), 0);
        assert_eq!(count_tokens("日本語"), 0);
        assert_eq!(count_tokens("v2.1"), 2);
    }
}
cli.rs
// Integration tests: compiled as a separate crate, so they see only the public API.
use tokstat::tally::Tally;

#[test]
fn malformed_lines_are_counted_not_fatal() {
    let mut t = Tally::default();
    for l in [r#"{"user":"a","text":"one two"}"#, "not json", r#"{"user":"b","text":"x"}"#, r#"{"user":17,"text":"x"}"#] {
        t.add_line(l);
    }
    assert_eq!((t.lines, t.ok, t.malformed, t.first_bad), (4, 2, 2, Some(2)));
    assert_eq!(t.top(5), vec![("a", 2), ("b", 1)]);
}

#[test]
fn binary_matches_the_root_spec() {
    let out = std::process::Command::new(env!("CARGO_BIN_EXE_tokstat"))
        .arg("../chat.jsonl")
        .output()
        .unwrap();
    let s = String::from_utf8(out.stdout).unwrap();
    assert!(s.starts_with("lines 2000  ok 1992  malformed 8 (first at line 53)"), "{s}");
}
$ cargo test 2>&1 | grep -E "Running|Doc-tests|^test |test result"
     Running unittests src/lib.rs (target/debug/deps/tokstat-c8b30a7fcc644835)
test tokenize::tests::edge_cases ... ok
test tokenize::tests::private_helper ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in <time>
     Running unittests src/main.rs (target/debug/deps/tokstat-59f844e4a80c39dc)
test result: ok. 0 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in <time>
     Running tests/cli.rs (target/debug/deps/cli-19823db216c0559e)
test malformed_lines_are_counted_not_fatal ... ok
test binary_matches_the_root_spec ... ok
test result: ok. 2 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in <time>
   Doc-tests tokstat
test src/tokenize.rs - tokenize::count_tokens (line 5) ... ok
test result: ok. 1 passed; 0 failed; 0 ignored; 0 measured; 0 filtered out; finished in <time>

A failing test, to see what assert_eq! reports (it prints both sides and your message; #[should_panic] tests that a panic happens):

failing_test.rs
fn count_tokens(text: &str) -> usize {
    text.split(' ').count() // bug: two spaces in a row make an empty "token"
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn single_spaces() {
        assert_eq!(count_tokens("a b c"), 3);
    }

    #[test]
    fn double_space() {
        assert_eq!(count_tokens("a  b"), 2, "two words separated by two spaces");
    }

    #[test]
    #[should_panic(expected = "index out of bounds")]
    fn out_of_bounds_panics() {
        let v: Vec<u32> = vec![];
        let _ = v[0];
    }
}
$ rustc --edition 2024 --test failing_test.rs -o failing_test && ./failing_test

running 3 tests
test tests::single_spaces ... ok
test tests::double_space ... FAILED
test tests::out_of_bounds_panics - should panic ... ok

failures:

---- tests::double_space stdout ----

thread 'tests::double_space' (16491396) panicked at failing_test.rs:16:9:
assertion `left == right` failed: two words separated by two spaces
  left: 3
 right: 2


failures:
    tests::double_space

test result: FAILED. 2 passed; 1 failed; 0 ignored; 0 measured; 0 filtered out; finished in <time>

[exit code 101]

The equivalents of pytest's extras: cargo test name_filter runs matching tests; -- --nocapture shows println! output; proptest does property-based testing like Hypothesis; insta does snapshot tests. Benchmarks use criterion. What to test, and why, is on Testing and quality.