21.1 A Quick Comparison: C’s switch
vs. Rust’s match
In C, a switch
statement is restricted mostly to integral or enumeration values. It can handle multiple cases and a default
, but it has some well-known pitfalls:
- Fall-through hazards, requiring explicit
break
statements to avoid accidental case continuation. - Limited pattern matching, focusing on integer or enum comparisons only.
- Non-exhaustive by design—you can omit cases and still compile.
Rust’s match
, on the other hand:
- Enforces Exhaustiveness: You must cover every variant of an enum or use a catch-all wildcard (
_
). - Handles Complex Data: You can destructure tuples, structs, enums, and more right within the pattern.
- Allows Boolean Guards: Add extra conditions to refine when a branch matches.
- Binds Sub-values: Extract parts of the matched data into variables automatically.
Because of this, match
in Rust is both safer and more expressive than a typical C switch
.