Make every case count.
Use exhaustive matching and keep wildcard cases honest.
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.
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)));
}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.
cargo run -p lesson_pattern_matching03 Mind the boundary
04 Your next build
Classify a score of 0 as empty, 1 through 9 as small, and every other u32 as large.
Reveal one possible solution +
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
What does a match guard add?
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.