π
World 6 Β· Choices & Magic Sorting
A Quick Peek (if let)
Sometimes you donβt want the whole sorting hat ceremony. You just want to take a quick
peek inside a box to see if thereβs something in it. π Thatβs exactly what if let is
for!
The Big Idea
if let is a shortcut for match when you only care about
one case. It's perfect for peeking inside an Option to grab a
value if it's there.
The long way with match
Remember Option? Itβs Some(value) when thereβs something, or None when itβs empty.
With match, peeking inside looks like this:
match treasure {
Some(gold) => println!("Found {} gold!", gold),
None => {}
}
That None => {} line does nothing β we only added it because match makes us cover
every case. A bit of wasted typing! π
The quick way with if let
if let lets us skip the case we donβt care about. We say: βif this value is Some with
something inside, give me that something and run my code.β
Think of it like thisβ¦
if let is like checking a delivery box. π¦ If something's inside, you take it out
and use it. If it's empty, you just close it and move on.