Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ MODEL THE DOMAIN
BUILD NOTE 17 / 53

Make every case count.

Use exhaustive matching and keep wildcard cases honest.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

01 Understand the contract

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.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/pattern-matching/src/main.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)));
}
↳ EXPECTED OUTPUT
diagonal / x-axis
  1. 1

    The origin case appears before the broader diagonal case.

  2. 2

    The guard checks a relationship after destructuring.

  3. 3

    The wildcard completes coverage for all other coordinates.

From the extracted rust-workbench folder
cargo run -p lesson_pattern_matching

03 Mind the boundary

04 Your next build

A SMALL MISSION

Classify a score of 0 as empty, 1 through 9 as small, and every other u32 as large.

Reveal one possible solution +
solutions/pattern-matching/src/main.rs
fn size(n: u32) -> &'static str {
    match n {
        0 => "empty",
        1..=9 => "small",
        _ => "large",
    }
}
fn main() {
    assert_eq!(size(0), "empty");
    assert_eq!(size(9), "small");
    assert_eq!(size(10), "large");
}

05 Check your reasoning

QUICK SIGNAL CHECK

What does a match guard add?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.