Chapter 21: Patterns and Pattern Matching
In Rust, patterns are a powerful mechanism to check whether values conform to certain shapes and, at the same time, to bind parts of those values to new variables. You’ll encounter patterns in many parts of the language, including:
- Variable Declarations
- Function and Closure Parameters
match
Expressionsif let
,while let
, andlet else
By ensuring that you handle every variant of an enum or other data structure, Rust’s pattern matching helps you avoid missing cases in complex branching scenarios. Compared to C’s switch
—which is restricted primarily to integers—Rust’s pattern matching is far more flexible. You can destructure complex data types, match against multiple patterns, and use boolean guards. This chapter introduces Rust’s patterns, highlights how they contrast with C-style flow control, and shows you how to apply them effectively in real Rust programs.