๐Ÿงฉ Rust Patterns

  • patterns consume values
  • simple identifiers become local variables in the match arm

Types

  • Literal
    • matches an exact value / const
    • e.g. 100, "name"
  • Range
    • matches any value in range
    • e.g. 0 ..= 10, 'a' .. 'e'
  • Wildcard
    • matches anything: _
  • Variable
    • Like wildcard, but moves/copies val into var
    • e.g. name
  • Tuple
    • e.g. (key, value)
  • Struct
    • e.g. StructName { field1: 12, field2}, StructName { field1: 12 ..}
  • ref variable
    • Like Variable, but borrowing the val instead of moving/copying
    • e.g. ref name
  • Subpattern
    • Matches pattern right of @, using var name to left
    • e.g. digit @ 0 ..=99, ref count @ .. 50
  • Guards
    • Extra condition if CONDITION between pattern and arm
    • e.g. Some(name) if name == "John" => ...
  • More on in chapter 10 of Programming Rust, 2nd edition

Where to use

  • match
  • In place of an identifier (like JS destructuring)

Example