21.2 Overview of Patterns

Rust supports a wide variety of patterns:

  • Literal Patterns: Match exact values, like 1, 'x', or "hello".
  • Identifier Patterns: Match anything and bind it to a variable (e.g., x).
  • Struct Patterns: Destructure structs, such as Point { x, y }.
  • Enum Patterns: Match specific enum variants, like Color::Red.
  • Tuple Patterns: Match and unpack tuple elements, for example (x, y).
  • Slice and Array Patterns: Match array or slice contents, such as [first, rest @ ..].
  • Reference Patterns: Match a reference, optionally binding the dereferenced value.
  • Wildcard Patterns (_): Match any value, ignoring its contents.

Patterns appear in these places:

  1. match Expressions: Rust’s exhaustive branching tool.
  2. if let, let else, while let: Concise forms for matching a single pattern.
  3. let Bindings: Destructure data when binding variables.
  4. Function and Closure Parameters: Unpack arguments directly in parameter lists.

Additionally, Rust offers shorthand for struct and enum fields that share the same name as local variables (for example, field_name instead of field_name: field_name). You can also use constants in place of numeric or string literals in your patterns to keep your code base consistent.