Sub topic 11
Fixing non-exhaustive matches
This chapter assumes you know Rust enums and match syntax, and that you can read the layout of a rustc diagnostic from earlier chapters. It covers error E0004, which appears when a match does not handle every possible value.
Why the compiler requires every case
A match must be exhaustive. Every value the scrutinee (the expression being matched) can hold has to be covered by some arm. If one case is missing, the program could reach a state with no code to run. Rust rejects this at compile time instead of failing at run time.
Here is a traffic light enum with a match that skips one variant.
enum Light {
Red,
Yellow,
Green,
}
fn action(light: Light) -> &'static str {
match light {
Light::Red => "stop",
Light::Green => "go",
}
}
fn main() {
println!("{}", action(Light::Yellow));
}Reading the diagnostic
Run cargo check. The error looks like this (details vary slightly by compiler version):
error[E0004]: non-exhaustive patterns: `Light::Yellow` not covered
--> src/main.rs:8:11
|
8 | match light {
| ^^^^^ pattern `Light::Yellow` not covered
|
note: `Light` defined here
= note: the matched value is of type `Light`
help: ensure that all possible cases are being handled by adding a match arm with a wildcard pattern or an explicit pattern as shown
|
10 ~ Light::Green => "go",
11 ~ Light::Yellow => todo!(),
|The primary span points at the scrutinee, not at an arm. The label names the exact pattern that is missing. The note shows where the type is defined, and the help gives a ready-made arm.
Three ways to fix it
Choose the fix based on what you want to happen for the missing case.
- Add an explicit arm. This is the best choice when the case has its own behavior. It keeps the compiler checking you later.
- Use a wildcard arm
_. This groups all remaining cases under one behavior. - Combine patterns with
|. This lets several values share an arm.
The explicit arm for our example:
enum Light {
Red,
Yellow,
Green,
}
fn action(light: Light) -> &'static str {
match light {
Light::Red => "stop",
Light::Yellow => "slow down",
Light::Green => "go",
}
}
fn main() {
println!("{}", action(Light::Yellow));
}Wildcards hide future errors
A _ arm silences the error, but it also silences future errors. Suppose you later add Light::FlashingRed to the enum. With an explicit arm for each variant, the compiler reports E0004 at every match that needs updating. With a _ arm, the new variant falls into the wildcard, and nobody is told.
enum Light {
Red,
Yellow,
Green,
}
fn can_go(light: Light) -> bool {
match light {
Light::Green => true,
_ => false,
}
}
fn main() {
println!("{}", can_go(Light::Green));
}This wildcard is reasonable here because "anything except green means no" is the real rule. Use _ when that is the intent. Avoid it as a quick way to quiet the compiler.
Non-enum scrutinees
Integers and other types with many values need a catch-all too, since the compiler cannot list every number.
fn describe(n: u8) -> &'static str {
match n {
0 => "zero",
1..=9 => "small",
10..=u8::MAX => "large",
}
}
fn main() {
println!("{}", describe(42));
}This compiles because the ranges cover all of u8 (0 to 255). If you wrote 10..=100, rustc would report that 101_u8..=u8::MAX is not covered. The error message tells you which range is missing.
Common mistakes
- Using
todo!()from the suggestion and forgetting it. It compiles, but panics when that arm runs. - Adding
_before the specific arms. Arms are checked in order, and the compiler warns about unreachable patterns that follow a wildcard. - Forgetting that
OptionandResultneed both variants (Some/None,Ok/Err).
Exercise
This function fails with E0004. Which pattern does rustc report as not covered, and what is one fix that keeps the compiler checking future variants? enum Dir { Up, Down, Left, Right } and fn name(d: Dir) -> &'static str { match d { Dir::Up => "up", Dir::Down => "down", Dir::Left => "left" } }
Show answer
rustc reports Dir::Right as not covered. Add an explicit arm, Dir::Right => "right",. An explicit arm is better than _ because adding another variant later will again cause E0004 at this match.