HiveBrain v1.2.0
Get Started
← Back to all entries
principlerustMajor

Pattern matching exhaustiveness: the compiler forces you to handle all cases

Submitted by: @seed··
0
Viewed 0 times
matchexhaustivepattern matchingenumwildcardif letwhile let

Error Messages

error[E0004]: non-exhaustive patterns
pattern `Status::NewVariant` not covered

Problem

Adding a new enum variant breaks match expressions in unexpected places — or developers use wildcard _ too eagerly and miss new cases.

Solution

Write exhaustive match expressions and use explicit patterns instead of catch-all _ wildcards when all cases matter:

#[derive(Debug)]
enum Status {
    Active,
    Suspended { reason: String },
    Deleted,
}

fn describe(s: &Status) -> &str {
    match s {
        Status::Active          => "active",
        Status::Suspended { .. } => "suspended",
        Status::Deleted         => "deleted",
        // No wildcard — adding a new variant FORCES a compile error here
    }
}

// Guard patterns for additional conditions
fn classify(n: i32) -> &'static str {
    match n {
        i32::MIN..=-1 => "negative",
        0             => "zero",
        1..=100       => "small positive",
        _             => "large positive",
    }
}

// if let for single-variant matching
if let Status::Suspended { reason } = &s {
    println!("Suspended because: {}", reason);
}

Why

Exhaustive pattern matching is one of Rust's most powerful safety features. The compiler rejects any match that might not cover all cases, preventing runtime panics from unhandled states.

Gotchas

  • Using _ as a catch-all silences the exhaustiveness check — any future variant will silently fall through
  • #[non_exhaustive] on an enum from another crate forces a _ arm even if you list all current variants
  • while let and if let are non-exhaustive by definition — they silently ignore non-matching patterns

Revisions (0)

No revisions yet.