Sub topic 4
Letting the compiler check every case
This chapter covers exhaustiveness checking. It assumes you can define an enum with data-carrying variants and write a basic match, and that you can build and run a program with cargo.
What exhaustiveness means
A match must cover every possible value of the type it inspects. If one variant has no arm, the program does not compile. This rule is called exhaustiveness checking.
The check happens at compile time. A missing case is a build error, not a runtime surprise.
enum Shape {
Circle { radius: f64 },
Rectangle { width: f64, height: f64 },
Triangle(f64, f64, f64),
}
impl Shape {
fn area(&self) -> f64 {
match self {
Shape::Circle { radius } => std::f64::consts::PI * radius * radius,
Shape::Rectangle { width, height } => width * height,
Shape::Triangle(a, b, c) => {
let s = (a + b + c) / 2.0;
(s * (s - a) * (s - b) * (s - c)).sqrt()
}
}
}
}
fn main() {
let shapes = [
Shape::Circle { radius: 1.0 },
Shape::Rectangle { width: 2.0, height: 3.0 },
Shape::Triangle(3.0, 4.0, 5.0),
];
for shape in &shapes {
println!("{:.2}", shape.area());
}
}All three variants have an arm, so this compiles and prints 3.14, 6.00, and 6.00.
What the error looks like
Delete the Triangle arm and the compiler stops with error E0004, "non-exhaustive patterns". It names the missing case, for example `patterns &Shape::Triangle(, , _) not covered`.
Why this helps when code changes
The check matters most during maintenance. Suppose you add a Square(f64) variant to Shape. Every match on Shape that has no wildcard stops compiling. The compiler gives you a list of places to update, so you cannot forget one.
Wildcards and their cost
The _ pattern matches anything not already covered. It satisfies the check, but it also turns off the safety net for that match.
enum Shape {
Circle { radius: f64 },
Rectangle { width: f64, height: f64 },
Triangle(f64, f64, f64),
}
fn is_round(shape: &Shape) -> bool {
match shape {
Shape::Circle { .. } => true,
_ => false,
}
}
fn main() {
println!("{}", is_round(&Shape::Circle { radius: 2.0 }));
println!("{}", is_round(&Shape::Triangle(3.0, 4.0, 5.0)));
}If you later add a round variant such as Ellipse, this function silently returns false for it. The compiler cannot warn you, because _ already covers it.
Use these guidelines:
- Prefer listing every variant when each one needs a deliberate decision.
- Use
_when the remaining cases truly share one behavior, and that behavior is unlikely to change. - Avoid
_in code where a new variant should force a review.
Exhaustiveness beyond enums
The rule applies to every type, not only enums. Integers have too many values to list, so a match on one needs a range or a wildcard.
fn describe(n: u8) -> &'static str {
match n {
0 => "zero",
1..=9 => "single digit",
10..=255 => "two or more digits",
}
}
fn main() {
println!("{}", describe(0));
println!("{}", describe(42));
}The ranges cover every u8 value from 0 to 255, so no wildcard is needed. Change the last range to 10..=254 and the build fails, because 255 is uncovered.
Guards and the check
The compiler does not evaluate the condition of a match guard when it checks coverage. An arm with an if guard therefore does not count as covering its pattern. A match whose only arms for a variant are guarded still needs a final unguarded arm.
Common mistakes
- Adding
_ => {}just to silence an error. This hides the missing case instead of handling it. - Expecting a guard to prove coverage. The compiler treats a guarded arm as possibly not matching.
- Placing
_first. Arms are tried in order, so later arms become unreachable, and the compiler warns about it.
Exercise
A function matches on a Shape and uses _ => 0.0 as its last arm. You then add a new variant Square(f64). Does the code still compile, and what is the risk?
Show answer
It still compiles, because _ covers the new variant. The risk is that Square silently gets the 0.0 result, and the compiler gives no warning. Listing each variant explicitly would make the compiler report the missing Square arm instead.
Exercise
Why does match n { 0 => "zero", 1..=9 => "digit" } fail to compile when n is a u8?
Show answer
The arms cover only 0 through 9. Values 10 through 255 have no arm, so the compiler reports a non-exhaustive match. Adding _ => "larger" or the range 10..=255 fixes it.