🧩
World 19 Β· Patterns Everywhere

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.

The Big Idea A pattern is a shape you compare against your data. If the data fits the shape, Rust can unpack the pieces inside and even pick what to do next.

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. πŸŽ‰

Think of it like this… Unpacking a tuple is like opening a backpack that always has your headphones in the left pocket and your keys in the right. The pattern lets you grab both at once and give them 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. ⭐

Ferris says: A match must cover every possibility. The _ arm is like an "everything else" basket, so nothing gets left out.
Try this! Change 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?

You learned… A pattern is a shape you hold up to your data. You can unpack a tuple with 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! πŸ”Ž