21.2 Overview of Patterns
Rust’s patterns are versatile and take many shapes:
- Literal Patterns: Match exact values (e.g.,
42,true, or"hello"). - Identifier Patterns: Match anything, binding the matched value to a variable (e.g.,
x). - Struct Patterns: Destructure structs, such as
Point { x, y }. - Enum Patterns: Match specific variants, like
Some(x)orColor::Red. - Tuple Patterns: Unpack tuples into their constituent parts, e.g.,
(left, right). - Slice & Array Patterns: Match array or slice contents, for example
[first, rest @ ..]. - Reference Patterns: Match references, optionally binding the dereferenced value.
- Wildcard Patterns (
_): Ignore any value you don’t need to name explicitly.
Patterns show up in:
matchExpressions (the most powerful form of branching).if let,while let, andlet else(convenient one-pattern checks).letBindings (destructuring data when declaring variables).- Function and Closure Parameters (unpack arguments right in the parameter list).