Patterns & Matching
You know those shape-sorter puzzles where a star block only fits through the star hole and a circle block only fits through the round hole? Rust has something just like that for your data. Itβs called pattern matching. π§©
A pattern is a little shape you hold up to your data to say βdo you look like this?β If it matches, Rust can pull the pieces apart for you and let you use them.
Patterns are everywhere
Youβve already used patterns without realizing it! Patterns show up in lots of places in Rust:
- in
let, to give names to values - in
match, to choose what happens - in
if let, to peek at one shape - even in the inputs of a function
Unpacking a tuple
A tuple is just a few values packed together in one box, like (3, 7). With
a pattern, you can open the box and name each piece at the same time. π¦
See how it works? The line let (x, y) = point; is a pattern. It says βthis box
has two things β call the first one x and the second one y.β One line, two
new names. π
Matching with ranges
Now for the shape-sorter part. The match tool checks your value against one shape
after another until one fits. You can even match a whole range of numbers with
1..=5, which means β1, 2, 3, 4, or 5.β The little _ at the end is a catch-all
that means βanything else.β
Since score is 4, it fell into the 1..=5 arm, just like a star block
finding its star hole. The other arms were skipped. β
match must cover every possibility. The
_ arm is like an "everything else" basket, so nothing gets left out.
score to 8 and press βΆ Run. Which
arm catches it now? Then try 100 and see the catch-all do its job.
Quick quiz
What does the pattern 1..=5 match?
let (x, y) = point; and choose what to do with
match, using ranges like 1..=5 and the catch-all _.
Next up: we dig deeper into match guards and binding for even smarter
matching! π