Skip to chapter content
navan✳THE BUILD LABRUST / GUIDE
0/26 read
CHAPTER 07 / 21 · DATA AND MODELS

Enums and patterns.

Represent alternatives as data and make every case visible.

BY NAVAN SAMILONG READRUST 2024THEORY FIRST
01 / THE MENTAL MODEL

The idea behind the syntax.

An enum says a value is exactly one of several variants. Unlike a loose string tag, each variant can carry data of its own shape. A Result can contain either success data or an error; an Option can contain either a value or absence. The type system keeps these alternatives connected, so a caller cannot accidentally read success data from the error case.

match examines a value and chooses an arm whose pattern fits. Each arm can bind the data inside a variant. A match must be exhaustive, which means adding a new variant can expose every place that needs a decision. if let and let else are useful when one case matters and the rest share a simpler route, but a full match is often clearer when all cases carry meaning.

02 / THE RULES

What Rust is checking.

Patterns appear beyond match: let bindings, function parameters, for loops, and conditional forms can destructure tuples, structs, and variants. A pattern may move a value, borrow it with ref-like behavior, or ignore part with _. The choice matters when the surrounding code still needs the original owner. Guards add a Boolean condition to a matching arm but do not replace structural coverage.

Option<T> makes absence explicit. Instead of a null reference that any operation might unexpectedly encounter, a function returning Option<T> forces its caller to decide what None means. The examples show how patterns turn that decision into readable control flow. The key idea is not the syntax alone; it is choosing a data model where invalid or missing states cannot quietly masquerade as ordinary values.

03 / CODE, EXPLAINED

See the rule in context.

Each example isolates one part of the model. Follow the bindings, types, ownership transfers, and possible outcomes line by line.

EXAMPLE 01

Enums & data-bearing variants

An enum describes one of several variants, and each variant can carry a different data shape. This is useful for states such as queued, running with a worker ID, or failed with a message. A pair of booleans could express contradictory combinations; an enum can make those states unrepresentable. Pattern matching inspects the variant and binds its data. Derive traits only when their behavior fits the data, and prefer domain types to magic strings for closed sets of choices.

enums.rs
enum Job {
    Queued,
    Running { worker: u32 },
    Failed(String),
}
fn describe(job: Job) -> String {
    match job {
        Job::Queued => "queued".into(),
        Job::Running { worker } => format!("worker {worker}"),
        Job::Failed(reason) => format!("failed: {reason}"),
    }
}
fn main() {
    println!("{}", describe(Job::Running { worker: 7 }));
    assert_eq!(describe(Job::Queued), "queued");
    assert_eq!(describe(Job::Failed("offline".into())), "failed: offline");
}
OUTPUT
worker 7
  1. Running carries a named worker field.
  2. Failed owns its message.
  3. The match handles every variant.

The boundary: Do not hide a useful domain enum behind arbitrary strings if callers need exhaustive checks.

EXAMPLE 02

match, guards & destructuring

match compares a value against patterns in order and must cover every possible case. Patterns can destructure tuples, structs, and enums, while guards add a boolean condition. A wildcard catches remaining cases but can also hide future domain changes. Prefer explicit variants when adding a new enum variant should force you to revisit the behavior. Matching a reference lets you inspect borrowed data without consuming the owner.

pattern-matching.rs
fn classify(point: (i32, i32)) -> &'static str {
    match point {
        (0, 0) => "origin",
        (x, y) if x == y => "diagonal",
        (_, 0) => "x-axis",
        _ => "elsewhere",
    }
}
fn main() {
    println!("{} / {}", classify((2, 2)), classify((3, 0)));
}
OUTPUT
diagonal / x-axis
  1. The origin case appears before the broader diagonal case.
  2. The guard checks a relationship after destructuring.
  3. The wildcard completes coverage for all other coordinates.

The boundary: Match order matters: an early broad pattern can make a later case unreachable.

EXAMPLE 03

Option & absent values

Option<T> is either Some(T) or None. It distinguishes a present value from absence without borrowing a magic integer or empty string for that role. match and if let let you handle the variants. map transforms the present case, and_then chains optional operations, and unwrap_or supplies a fallback. Use unwrap only where an invariant justifies a panic; user input and lookup misses normally deserve a handled result. An Option<&T> can represent a borrowed lookup without cloning.

option.rs
fn main() {
    let values = [10, 20];
    let doubled = values.get(1).map(|value| value * 2);
    println!("present={doubled:?}");
    println!("fallback={}", values.get(8).copied().unwrap_or(0));
    if let Some(first) = values.first() {
        println!("first={first}");
    }
}
OUTPUT
present=Some(40)
fallback=0
first=10
  1. get returns an optional borrowed element.
  2. map transforms only the Some case.
  3. copied converts Option<&i32> to Option<i32> before applying a fallback.

The boundary: None is not a generic failure explanation. Use Result when the caller needs to know why an operation failed.

04 / THE CONNECTION

Keep this model.

Enums describe the cases that can exist; patterns force code to account for those cases at the point of use.

Finished reading?
Built with curiosity. By Navan Sami. ↗Rust · The rules behind the code.