πŸ‘€
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.

Let’s peek inside a box

</div> See how the first box had `Some(100)`, so we pulled out `100` and used it. The second box was `None`, so the `else` part ran instead. πŸŽ‰
Ferris says: You can add else to if let for "what to do when there's nothing." It's like a backup plan! πŸ¦€
Watch out! The value gold only exists inside the if let braces. Once you leave the curly braces, it's gone β€” so use it while you're in there!
Try this! Change Some(100) to None and run it. What does the first peek do now? (Hint: it has no else, so it just stays quiet! 🀫)
## Quick quiz

When is if let the best choice?

Yes! if let is the quick peek for when just one case matters. πŸ‘€

You learned… if let is a friendly shortcut for match when only one case matters, like pulling a value out of Some, with an optional else for the empty case. You've finished World 6: Choices & Magic Sorting β€” get ready for your next adventure! πŸš€