Chapter 21: Patterns and Pattern Matching
In Rust, patterns provide an elegant way to test whether values fit certain shapes and simultaneously bind sub-parts of those values to local variables. While patterns show up most notably in match
expressions, they also appear in variable declarations, function parameters, and specialized conditionals (if let
, while let
, and let else
). Compared to C’s switch
—which is mostly limited to integral and enumeration types—Rust’s patterns are far more flexible, allowing you to destructure complex data types, handle multiple patterns in a single branch, and apply boolean guards for additional checks.
This chapter explores the many facets of pattern matching in Rust, highlights its differences from the C-style approach, and demonstrates how to leverage patterns effectively in real code.