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.
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!"),
}
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.β
_ 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.
_ 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!
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. π§Ί
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! π