Lesson 6.3 · 11 min
Lookup by key: HashMap
A Vec finds things by position. But "what did I tell you about pizza?" is a question about a name, not a position. For lookups by name, Rust has the HashMap, and with one Chatterbox can finally remember a fact and recall it later.
Adds to Chatterbox/remember and /recall, with a HashMap.
Remembering by name
Chatterbox keeps every message in a Vec now, in order. But suppose you tell it /remember pizza pepperoni please and, much later, ask /recall pizza. It could walk the whole history looking for the word, but that gets slower as the history grows, and it is the wrong shape: you are not asking "what was said at position 12", you are asking "what goes with the name pizza".
A HashMap is a table for exactly that. Every row has a key (the thing you look up by) and a value (what you find). You write the type as HashMap<String, String>: the keys are Strings and the values are Strings too. It lives in the standard library (the toolbox that comes with Rust), but it is not loaded automatically, so a program that wants one starts with use std::collections::HashMap;.
The owner rule again: the map owns its keys and its values. When you insert a String, it moves into the table.
$ cargo run
Some("pepperoni please")
Noneget returns an Option (lesson 5.4): Some(…) holding a borrow of the value when the key is there, None when it is not. A name nobody has used is not an error, just an empty answer, and you match on it like any other Option.
What if you remember the same name twice?
What does this program print?
Some("pepperoni")Some("extra cheese")None
Reveal the answer
The program prints: Some("extra cheese") A key appears once in a map. A second insert with the same key replaces the old value, so the table holds one row for "pizza" and its value is the newer one. In Chatterbox that means remembering a fact again simply updates it.
No order
A HashMap does not remember the order you inserted rows, and the order it walks them in can change from one run to the next. That is the price of fast lookup. If you want to print a map's keys in a stable order, copy them into a Vec and sort it. Chatterbox does exactly that when you type /recall with no name.
Chatterbox v0.6: /remember and /recall
Here is the whole program after this lesson, new lines in green. The help text now lists /remember <name> <fact> and /recall <name>.
use std::collections::HashMap;at the top, and before the looplet mut facts: HashMap<String, String> = HashMap::new();: names to facts.- Three new variants.
Remember(String, String)carries a name and its fact.Recall(Option<String>)carries a name, orNonefor a bare/recall.Usage(String)carries the right way to type a command, for when/rememberis missing a part. - In
parse,/rememberusesarg(lesson 5.4) twice. On/remember pizza pepperoni please, the firstarggivespizza pepperoni please; the name is itsfirst_word, and a secondarggives the fact,pepperoni please. If either part is missing, the answer isUsage. - The
Rememberarm prints "got it" first and only then callsfacts.insert(key, fact). The order matters:insertmoves both Strings into the map, and after that they are not yours to print. Recall(Some(key))asksfacts.get(&key)(the&lends the name toget, which only needs to look at it) and matches on the Option: the fact, or "I don't know anything about …".Recall(None)lists every name.facts.keys()walks the names; each one is pushed onto a Vec as a borrowed&str(as_str()lends a String as a&str). Thennames.sort(), andnames.join(", ")glues the names into one piece of text with a comma between each.
Sam /remember pizza pepperoni please /recall pizza /recall cat /remember dog woof /recall /quit
Chatterbox v0.6 What should I call you? Hi Sam! I'm Chatterbox. Ask me anything. bot: got it: pizza is pepperoni please bot: pizza is pepperoni please bot: I don't know anything about cat bot: got it: dog is woof bot: I remember: dog, pizza bot: bye, Sam! messages so far: 0
Show the whole program (open it after you have tried the exercise below: it contains the answer)
Download this version (zip)Unzip, then cargo run inside the folder.
This is the whole Chatterbox program with the /remember arm of parse taken out. Write it again: split /remember pizza pepperoni please into the name pizza and the fact pepperoni please, and give back Command::Usage with the text /remember <name> <fact> when a part is missing.
This is the whole Chatterbox program with the /remember arm of parse taken out. Write it again: split /remember pizza pepperoni please into the name pizza and the fact pepperoni please, and give back Command::Usage with the text /remember <name> <fact> when a part is missing.
Hidden tests (5): a_name_with_no_fact_shows_usage bare_remember_shows_usage extra_spaces_do_not_count recall_is_untouched splits_name_and_fact
This exercise runs real Rust in your browser through the official Rust Playground, so it needs JavaScript.
Another job for a map: counting
A HashMap is also the natural tool for counting: the key is the thing you count and the value is how many times you have seen it. Counting needs three steps: find the row, make one starting at 0 if it does not exist, then add 1. Rust does all three in one line.
counts.entry(key) points at the row for that key, whether it exists yet or not. .or_insert(0) says "if there is no row, create it with 0", and hands back a borrow of the number that lives in the table. The * in front means "the number the borrow points to", so += 1 changes the number inside the map.
The next program also reads a value with square brackets, counts["/help"]. That is quick, but just like [ ] on a Vec, it crashes the program (a panic) if the key is not there. Use get whenever the key might be missing.
$ cargo run
/help typed 3 times
/say typed 1 timesIf you have coded before
This is counts[key] = counts.get(key, 0) + 1, or collections.Counter, in one expression. Square brackets on a HashMap (counts["/help"]) work like Python's and also crash on a missing key, so use get when the key may be absent.
A smaller exercise to practise counting, on a cut-down Message. In a group chat with several people, every author would get a row. Write count_by_author. Walk the history and return a map from each author name to how many messages that author wrote. Like the exercises in lessons 6.1 and 6.2, it takes the history as &[Message], a borrowed view of the list.
A smaller exercise to practise counting, on a cut-down Message. In a group chat with several people, every author would get a row. Write count_by_author. Walk the history and return a map from each author name to how many messages that author wrote. Like the exercises in lessons 6.1 and 6.2, it takes the history as &[Message], a borrowed view of the list.
Hidden tests (3): counts_each_author unknown_author_is_absent empty_history_has_no_rows
This exercise runs real Rust in your browser through the official Rust Playground, so it needs JavaScript.
What you have now
Chatterbox answers two kinds of question: "what was said, in what order" (the history, a Vec) and "what goes with this name" (the facts, a HashMap). Pick the container by the question you ask: by position, or by name. Next: small functions you can write right where you need them, which give Chatterbox a /find command.
Say it out loud, then reveal
What does <code>facts.get("cat")</code> return when nobody ever remembered cat?Reveal
None. A missing key is an ordinary empty answer, not a crash.Why does the <code>Remember</code> arm print "got it" before it calls <code>facts.insert(key, fact)</code>?Reveal
insert moves both Strings into the map. After it, key and fact belong to the map, so they can no longer be used to print.Why does a bare <code>/recall</code> sort the names before printing them?Reveal
What does <code>*counts.entry(key).or_insert(0) += 1</code> do?Reveal
That is lesson 6.3. Tick it off so the course remembers where you are.
Go deeper
Questions people ask
What do I need to write to use HashMap in Rust?
Add use std::collections::HashMap; at the top of the file. It comes with Rust in the standard library, but it is not loaded automatically.
How do I look up a value in a Rust HashMap?
Call get with the key. It returns an Option: Some holding a borrow of the value when the key is there, and None when it is not.
What happens if I insert the same key twice?
The second value replaces the first. A map holds at most one value per key.
Is a Rust HashMap like a Python dict?
Yes for lookup by key. Differences: all keys share one type, all values share one type, and iteration order is not something you should rely on.