7.2 The match Statement
Rust’s match statement is a powerful control flow construct that goes far beyond C’s switch. It allows you to match on patterns, not just integer values, and it enforces exhaustiveness by ensuring that all possible cases are handled.
fn main() { let number = 2; match number { 1 => println!("One"), 2 => println!("Two"), 3 => println!("Three"), _ => println!("Other"), } }
Key Points:
- Patterns:
matchcan handle complex patterns, including ranges and tuples. - Exhaustive Checking: The compiler verifies that you account for every possible value.
- No Fall-Through: Each match arm is independent; you do not use (or need) a
breakstatement.
Comparison with C’s switch:
- Rust’s
matchavoids accidental fall-through between arms. - Patterns in
matchoffer far more power than integer-basedswitchcases. - A wildcard arm (
_) in Rust is similar todefaultin C, catching all unmatched cases.
We will delve deeper into advanced pattern matching in a later chapter.