Sub topic 4
Letting the compiler check every case
This chapter assumes you can define an enum, write a basic match, and read a Rust compiler error. Here you learn what the compiler checks when you write a match, how to keep that check useful, and which errors you will meet.
What exhaustiveness means
A match expression is exhaustive when every possible value of the matched type is handled by at least one arm. Rust requires this. If some value could reach the match and no arm accepts it, the program does not compile.
Take the Shape enum from earlier chapters, with Circle, Rectangle, and Triangle variants. Suppose you delete the Triangle arm from area. The compiler stops with this error:
error[E0004]: non-exhaustive patterns: `&Shape::Triangle(_, _, _)` not coveredThe message names the missing pattern. The & appears because the code matches on &self. The _ placeholders stand for the fields you did not mention.
The check happens at compile time, so a missing case cannot become a runtime crash or a silent fall-through. Other languages let a switch skip a case without complaint. Rust turns that mistake into a build failure.
How the check works
The compiler reads every arm and collects the patterns that can match without a guard. It then asks whether those patterns together cover the whole type. If they do not, it reports a witness: one example of a value that no arm accepts.
A complete example is a turning direction:
#[derive(Debug, Clone, Copy)]
enum Direction {
North,
East,
South,
West,
}
impl Direction {
fn turn_right(self) -> Direction {
match self {
Direction::North => Direction::East,
Direction::East => Direction::South,
Direction::South => Direction::West,
Direction::West => Direction::North,
}
}
}
fn main() {
let mut d = Direction::North;
for _ in 0..5 {
d = d.turn_right();
println!("{d:?}");
}
}Each variant has an arm, so the code compiles. If you later add a Direction::Up variant, every match on Direction that lacks a catch-all arm fails to compile. The compiler gives you a list of places to update.
The wildcard trade-off
The wildcard pattern _ matches anything, so it always makes a match exhaustive. That is its purpose, but it also turns off the safety net for the values it absorbs.
enum Light {
Red,
Yellow,
Green,
}
fn can_go_loose(light: &Light) -> bool {
match light {
Light::Green => true,
_ => false,
}
}
fn can_go_strict(light: &Light) -> bool {
match light {
Light::Green => true,
Light::Red | Light::Yellow => false,
}
}
fn main() {
for l in [Light::Red, Light::Yellow, Light::Green] {
println!("{} {}", can_go_loose(&l), can_go_strict(&l));
}
}Both functions behave the same today. Now add Light::FlashingRed. can_go_loose still compiles and quietly treats the new variant as false. can_go_strict fails to compile and forces you to decide.
Use these rules of thumb:
- List variants explicitly when a new variant should make you revisit the code.
- Use
_when the remaining values really are one uniform case, such as "any other number". - Be most careful with
_on enums you own and change often.
Exhaustiveness beyond enums
The check applies to every matched type, not only enums.
boolneeds bothtrueandfalse, or a wildcard.- Integers have many values, so you normally need
_. A set of ranges that covers the whole type is also accepted. - Tuples, structs, and nested enums are checked by combination.
fn bucket(n: u8) -> &'static str {
match n {
0..=99 => "low",
100..=255 => "high",
}
}
fn describe(a: Option<i32>, b: Option<i32>) -> String {
match (a, b) {
(Some(x), Some(y)) => format!("sum {}", x + y),
(Some(x), None) | (None, Some(x)) => format!("one value {x}"),
(None, None) => String::from("nothing"),
}
}
fn main() {
println!("{}", bucket(7));
println!("{}", bucket(200));
println!("{}", describe(Some(1), Some(2)));
println!("{}", describe(None, Some(5)));
println!("{}", describe(None, None));
}bucket has no wildcard because the two ranges together cover every u8 from 0 to 255. Change 100..=255 to 100..=254 and the compiler reports that 255_u8 is not covered.
describe matches on a pair of options. Two options give four combinations, and the three arms cover them all, because the or-pattern in the second arm handles two combinations at once. Delete the last arm and the compiler reports (None, None) as the uncovered case.
Guards do not count
A match guard is the if condition after a pattern. The compiler does not try to reason about what a guard expression means. An arm with a guard is treated as possibly not matching, so it never helps cover a type.
This function does not compile, even though the two guards seem to cover all integers:
match n {
x if x > 0 => "positive",
x if x < 0 => "negative",
}The compiler reports i32::MIN..=i32::MAX as not covered. The fix is to make the last arm unguarded:
fn sign(n: i32) -> &'static str {
match n {
x if x > 0 => "positive",
x if x < 0 => "negative",
_ => "zero",
}
}
fn main() {
println!("{} {} {}", sign(5), sign(-2), sign(0));
}The check is therefore conservative. It never accepts a match that could miss a value. It sometimes rejects one that you know is complete.
Arms are tried in order
Rust tests arms from top to bottom and runs the first one that matches. An arm that can never run, because earlier arms already cover everything it matches, produces a warning, unreachable pattern. The usual cause is a wildcard placed too early:
- A
_arm followed by more arms makes the later arms dead code. - Overlapping ranges are legal, but the first range wins in the overlap, and the compiler warns when the second range is fully covered.
Treat the warning as a bug report. It usually means the arm order is wrong or an arm is redundant.
Enums from other crates
A library author can mark a public enum with #[non_exhaustive]. This lets the library add variants later without breaking users. When you match on such an enum from another crate, the compiler requires a wildcard arm even if you list every variant that exists today. This is the one case where _ is mandatory on an enum.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `E0004 non-exhaustive patterns` naming a variant | An arm is missing | Add an arm for the named variant |
| `E0004` naming a numeric range | Integers matched without a catch-all | Add `_` or cover the full range |
| `E0004` although guards look complete | Guarded arms do not count | End with an unguarded arm |
| `unreachable pattern` warning | A wildcard or broader arm comes first | Reorder or remove the arm |
| New variant added, nothing breaks | A `_` arm absorbed it | Replace `_` with explicit variants |
Exercises
Exercise
You add a new variant Light::FlashingRed to the Light enum. Which of can_go_loose and can_go_strict fails to compile, and why does the other one still compile?
Show answer
can_go_strict fails with E0004 because its arms list Red and Yellow explicitly and no arm covers FlashingRed. can_go_loose still compiles because its _ arm matches every remaining variant, so the new variant silently returns false.
Exercise
Why does match n { x if x >= 0 => "non-negative", x if x < 0 => "negative" } on an i32 fail to compile, and how do you fix it?
Show answer
The compiler does not analyze guard conditions, so it treats both arms as possibly not matching and reports that values are not covered. Make the last arm unguarded, for example _ => "negative", or use range patterns such as 0..=i32::MAX and i32::MIN..=-1, which the compiler can check.