๐งฉ 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
- Variable
- Like wildcard, but moves/copies val into var
- e.g.
name
- Tuple
- 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 ยง