Chapter 21: Patterns and Pattern Matching
Patterns are a special syntax in Rust used for matching against the structure of types. They allow you to check if values conform to a certain shape, and if they do, you can bind parts of those values to variables. While most commonly associated with the powerful match
expression, patterns are ubiquitous in Rust, appearing also in let
statements, function parameters, if let
, while let
, let else
, and for
loops.
For C programmers, Rust’s pattern matching, especially within match
, significantly extends the capabilities of C’s switch
statement. While switch
is primarily limited to integers and enum constants, Rust patterns can destructure complex types like structs, tuples, and enums (including those with associated data), match against ranges or literals, handle multiple possibilities in one arm, and apply conditional logic using guards.
This chapter delves into the various forms of patterns, their use cases across the language, and how they compare to C’s switch
. Understanding patterns is fundamental to leveraging Rust’s expressiveness and safety features for writing concise and robust code.