21.1 Comparison: C switch vs. Rust match
The switch statement in C provides basic conditional branching based on the value of an expression, but it has several limitations compared to Rust’s match:
- Limited Types: C’s
switchworks reliably only with integral types (likeint,char) and enumeration constants. It cannot directly handle strings, floating-point numbers, or complex data structures. - Fall-through Behavior: By default, execution “falls through” from one
caselabel to the next unless explicitly stopped by abreakstatement. This is a notorious source of bugs ifbreakis accidentally omitted. - Non-Exhaustiveness: The C compiler typically does not enforce that all possible values of an enum or integer range are handled within a
switch. While warnings might be available, missing cases can lead to unhandled states and runtime errors. - Simple Comparisons:
caselabels only permit direct equality comparisons against constant values.
Rust’s match expression systematically addresses these points:
- Type Versatility:
matchworks with any type, including complex data structures like structs, enums, tuples, and slices. - Exhaustiveness Checking: The Rust compiler requires that a
matchexpression covers all possible variants for the type being matched (especially enums). This compile-time check eliminates entire classes of bugs related to unhandled cases. The wildcard pattern (_) can be used to explicitly handle any remaining possibilities. - No Fall-through: Each arm of a
matchexpression (PATTERN => EXPRESSION) is self-contained. Execution does not automatically fall through to the next arm, preventing related bugs. - Powerful Pattern Syntax:
matcharms use patterns that go far beyond simple equality checks. They can destructure data, bind values to variables, match ranges, combine multiple possibilities (|), and use conditional guards (if condition). - Value Binding: Patterns can extract parts of the matched value and bind them to new variables available only within the scope of the matching arm.
Overall, match provides a safer, more expressive, and more versatile tool for control flow based on the structure and value of data compared to C’s switch.