🎩
World 6 Β· Choices & Magic Sorting

match: The Sorting Hat

Imagine a magical sorting hat. 🎩 You put it on, it looks at you, and then it decides which house you belong in. Rust has its own sorting hat, and it’s called match.

The Big Idea match looks at a value and runs different code depending on what it finds β€” one branch for each possibility, just like the sorting hat picks a different house for each student.

How match works

You give match a value, then list the cases with little arrows =>. Rust checks them from top to bottom and runs the one that fits.

match my_light {
    Light::Red => println!("Stop!"),
    Light::Yellow => println!("Slow down!"),
    Light::Green => println!("Go!"),
}
Think of it like this… match is like a row of labeled mailboxes. A letter (your value) drops into the one box that matches its label. Each box does its own special job. πŸ“¬

Every case must be covered

The sorting hat can’t leave a student standing there with no house. In the same way, match must handle every possible value. If you forget one, Rust politely stops you and asks, β€œHey, what about this case?”

When you don’t want to list every single one, you can use _ (an underscore). It’s the catch-all β€” β€œanything else goes here.”

New word The catch-all _ matches everything you didn't already list. It's like a "lost and found" box for all the leftover cases. 🧺

A full example

Let’s let our traffic light speak! Run it and watch each light say its job.

Here’s match on plain numbers, using _ as the catch-all for everything else.

Watch out! The catch-all _ should go last. Rust reads cases top to bottom, so if _ came first it would gobble up everything before the other cases got a turn!
Try this! Change let dice = 6; to let dice = 3; and run it. Which branch catches it? 🎲

Quick quiz

What does _ do in a match?

Exactly! _ is the "everything else" box, so every possible value is covered. 🧺

You learned… match is Rust's sorting hat: it runs different code for each value, it must cover every case, and _ is the catch-all. Next up: A Quick Peek (if let) β€” a handy shortcut for when you only care about one case! πŸ‘€