π
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! π