🎯

Pattern Matching β€” Branching with match and if let

A superior alternative to switch/case, core Rust expression style

C/Java's switch-case only compares values. Rust's match destructures values while branching simultaneously.

match some_option {
    Some(value) => println!("got {value}"),
    None => println!("nothing"),
}

Extracting the value inside Some and branching happen at once. The compiler checks all cases are handled β€” miss one and it won't compile.

if let is match shorthand for when you care about only one pattern:

if let Some(value) = some_option {
    println!("got {value}");
}

Enums, tuples, structs, references β€” nearly every Rust type can be destructured via patterns.

Key Points

1

Value in match expression is matched against each arm pattern in order

2

Pattern destructures the value and binds to variables

3

Exhaustive β€” all possible cases must be handled to compile

4

_ (wildcard) handles remaining cases at once

Pros

  • Compiler catches missing cases
  • Value comparison + destructuring + binding in one step

Cons

  • Deeply nested patterns can reduce readability

Use Cases

Result/Option handling β€” explicitly branch on success/failure, some/none Enum-based state machines β€” define behavior per state via patterns