Sub topic 11
Fixing non-exhaustive matches
This chapter assumes you know basic Rust syntax, including enums and match, and that you can run cargo check. It covers error E0004, the compiler's report that a match does not handle every possible value. You will learn to read the message, choose a fix, and avoid fixes that hide future bugs.
What exhaustiveness means
A match must cover every value the matched expression can have. The compiler checks this at compile time. If any value has no arm, the program is rejected with E0004.
This is a feature. When you add a variant to an enum, the compiler can show you every match that now needs updating.
Here is the failing program from the plan:
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));
}Running cargo check produces a diagnostic like this (exact wording varies by compiler version):
error[E0004]: non-exhaustive patterns: `Light::Yellow` not covered
--> src/main.rs:9:11
|
9 | match light {
| ^^^^^ pattern `Light::Yellow` not covered
|
note: `Light` defined here
--> src/main.rs:1:6
|
1 | enum Light {
| ^^^^^
2 | Red,
3 | Yellow,
| ------ not covered
= 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
|
11 ~ Light::Green => "go",
12 ~ Light::Yellow => todo!(),
|Reading the diagnostic
Each part tells you something specific.
- Message. It names the uncovered pattern:
Light::Yellow. For larger types it may list several, or use_for "anything else". - Primary span. The caret marks the matched expression
light, not an arm. The error is about the wholematch. - Note. It points to the enum definition and labels the variant that has no arm.
- Help. It suggests an arm. The suggested body is
todo!(), which compiles but panics at run time. You still have to write the real behavior.
The fix: add the missing arm
The best fix is usually an explicit arm for each missing case:
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));
}This prints slow down. Now the compiler guarantees that all three variants are handled.
Choosing between an explicit arm and a wildcard
You can also end a match with a wildcard arm, _, which matches any value not matched earlier. Arms are checked from top to bottom, so _ must come last.
fn is_stop(light: &Light) -> bool {
match light {
Light::Red => true,
_ => false,
}
}This is correct when "everything else" really shares one behavior. It has a cost. If someone adds Light::Flashing later, this match still compiles, and Flashing silently falls into the _ arm. An explicit list would have produced E0004 and pointed you at the code to review.
| Approach | Compiler warns on new variants | Best when | Column |
|---|---|---|---|
| One arm per variant | Yes | Each variant needs its own behavior | |
| Or-pattern, such as `Light::Red \ | Light::Yellow` | Yes | Several known variants share behavior |
| Wildcard `_` | No | The remaining cases are truly irrelevant | |
| `todo!()` body | Yes, until replaced | You are sketching and will return |
An or-pattern joins several patterns with | in one arm and keeps the safety of explicit listing:
fn must_wait(light: &Light) -> bool {
match light {
Light::Red | Light::Yellow => true,
Light::Green => false,
}
}Beyond enums: integers, tuples, and ranges
E0004 is not limited to enums. The compiler also checks integers, booleans, tuples, and nested patterns.
An integer has too many values to list, so you need a range or a wildcard:
fn grade(score: u8) -> char {
match score {
90..=255 => 'A',
80..=89 => 'B',
0..=79 => 'C',
}
}
fn main() {
println!("{}", grade(85));
}This compiles because the three ranges cover every u8 from 0 to 255. If you changed the first range to 90..=100, the compiler would report that 101_u8..=u8::MAX is not covered. For a plain i32, nearly every match needs a _ arm, because covering the full range explicitly is impractical.
Tuples are checked by combination. This match is missing two cases:
fn describe(on: bool, ready: bool) -> &'static str {
match (on, ready) {
(true, true) => "go",
(false, _) => "off",
}
}The compiler reports (true, false) as not covered. The fix is to add that arm:
fn describe(on: bool, ready: bool) -> &'static str {
match (on, ready) {
(true, true) => "go",
(true, false) => "waiting",
(false, _) => "off",
}
}Option and Result
Matching on Option and Result is the most common place you meet E0004 in everyday code.
fn show(value: Option<i32>) -> String {
match value {
Some(n) => format!("got {n}"),
None => String::from("nothing"),
}
}If you drop the None arm, the compiler reports `pattern None not covered`. Handling both is the point of the type: the absence of a value cannot be forgotten.
When you only care about one case, use if let instead of a match with a throwaway arm:
fn print_if_present(value: Option<i32>) {
if let Some(n) = value {
println!("got {n}");
}
}if let is not checked for exhaustiveness, because ignoring the other cases is explicit in the syntax. A related form, let ... else, lets you handle the other case by leaving the function early:
fn double_or_zero(value: Option<i32>) -> i32 {
let Some(n) = value else {
return 0;
};
n * 2
}Match guards do not count
An arm with an if guard may fail even when its pattern matches, so the compiler does not treat it as covering that pattern.
fn sign(n: i32) -> &'static str {
match n {
x if x < 0 => "negative",
x if x >= 0 => "non-negative",
}
}You can see the two guards cover every integer, but the compiler does not reason about guard expressions. It reports that i32::MIN..=i32::MAX is not covered. Remove the condition from the last arm:
fn sign(n: i32) -> &'static str {
match n {
x if x < 0 => "negative",
_ => "non-negative",
}
}Non-exhaustive types from other crates
Library authors can mark an enum with #[non_exhaustive]. This lets them add variants later without breaking your code. The cost to you is that a match on such an enum from another crate must include a wildcard arm, even if you list every variant that exists today.
A decision process
Common mistakes
- Accepting the
todo!()suggestion and forgetting it. The program compiles and then panics on that input. Search fortodo!before you ship. - Putting
_first. Later arms become unreachable, and the compiler warns withunreachable pattern. Order arms from most specific to least specific. - Using
_on your own enums by habit. You lose the compiler's help when the enum grows. Prefer explicit arms or or-patterns for types you own. - Relying on guards for coverage. End with an arm that has no guard.
- Fixing the error by returning a default. If the missing case is a real error condition, return a
Resultor callunreachable!()with a message, so a mistake fails loudly.
Verifying your fix
Run cargo check after each change. When the E0004 error disappears, confirm that no new unreachable pattern warning appeared. If the message is unclear, rustc --explain E0004 prints a longer description with examples.
Exercise
This function fails with E0004. Which variant is missing, and what is a fix that keeps the compiler's protection if a variant is added later? enum Shape { Circle, Square, Triangle } fn sides(s: Shape) -> u32 { match s { Shape::Circle => 0, Shape::Square => 4, } }
Show answer
Shape::Triangle is not covered. Add an explicit arm, Shape::Triangle => 3, rather than a wildcard. Because every variant is listed, adding a fourth variant later produces E0004 again and shows you this match.
Exercise
Why does this match fail with E0004 even though the two arms look like they cover every i32, and how do you fix it? match n { x if x < 0 => "negative", x if x >= 0 => "non-negative", }
Show answer
The compiler does not analyze guard conditions, so a guarded arm never counts as covering its pattern. Remove the guard from the last arm and use a plain wildcard, for example _ => "non-negative", or x => "non-negative".