Enums & Pattern Matching

Enums and pattern matching are Rust’s tools for modeling closed sets of possibilities and handling every shape of data explicitly.

Concepts

Patterns

Antipatterns

Example

enum Input {
    Number(i32),
    Empty,
}
 
fn classify(input: Input) -> &'static str {
    match input {
        Input::Number(n) if n > 0 => "positive",
        Input::Number(_) => "non-positive",
        Input::Empty => "empty",
    }
}
 
fn main() {
    assert_eq!(classify(Input::Number(3)), "positive");
    assert_eq!(classify(Input::Empty), "empty");
}

Best practice

  • ✅ Model closed domain alternatives with Enums instead of strings or sentinel values.
  • ✅ Reach first for The match Expression when every case matters.
  • ✅ Use if let and let else only when ignoring or exiting on other cases is intentional.

Pitfalls

  • ⚠️ Do not lose Exhaustiveness by replacing meaningful matches with broad wildcards.
  • ⚠️ Do not mistake pattern bindings for equality checks; see Pattern Variable Shadowing.
  • ⚠️ Do not unwrap Option just to get at a payload; use patterns or combinators.

See also

Enums · Enum Variants with Data · Option · The match Expression · Patterns · Exhaustiveness · Destructuring · Match Guards · Binding with @ · if let · let else · Catch-All and Wildcard Patterns · Overbroad Catch-All Match Arms · Pattern Variable Shadowing

Sources