πŸ”‘
World 8 Β· Collections

Hash Maps: Matching Pairs

Imagine a phone book where you look up a friend’s name and instantly find their high score. πŸ“– You don’t read every page β€” you just flip right to the name. In Rust, that instant lookup book is called a hash map.

The Big Idea A hash map (written HashMap<K, V>) matches a key to a value β€” like matching a name to a score. The K is the key and the V is the value.

Opening the lookup book

Hash maps don’t come ready-to-go like vectors, so first you have to tell Rust where to find them with a use line. Then you can make an empty one.

Think of it like this… A hash map is like a coat-check at a party. You hand over your coat (the value) and get a numbered ticket (the key). Later, you show the ticket and get your exact coat back β€” almost instantly! 🎟️

Insert and look up

You add a pair with .insert(key, value). To find a value later, you use .get(&key). Rust wraps the answer in Some(...) to say β€œI found it!” β€” that’s Rust being careful in case the key isn’t there.

Ferris says: The if let Some(points) part means "if the name was really in the book, grab the score." If the name isn't there, Rust skips it safely instead of crashing. πŸ›‘οΈ
Watch out! Each key can only point to one value. If you insert the same name twice, the new score replaces the old one β€” like erasing and rewriting.
Try this! Add a third player with scores.insert("Gus", 80);, then change who to "Gus" and press β–Ά Run.

Quick quiz

In a HashMap, how do you find a value once you know its key?

Exactly! .get(&key) flips right to the matching value. πŸ“–

You learned… A hash map matches keys to values like a lookup book. You bring it in with use std::collections::HashMap;, add pairs with .insert, and find them with .get. You've packed your whole Collections backpack β€” next world, we head off on a brand-new adventure! πŸŽ’