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:
match
can 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
break
statement.
Comparison with C’s switch
:
- Rust’s
match
avoids accidental fall-through between arms. - Patterns in
match
offer far more power than integer-basedswitch
cases. - A wildcard arm (
_
) in Rust is similar todefault
in C, catching all unmatched cases.
We will delve deeper into advanced pattern matching in a later chapter.