Vibe Engines
YouTube

Vibe Engines is free, interactive AI engineering & system design — runs in your browser. Pick a learning path

Learn RustChapter 6: Collections

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.

insert puts a row in, get looks one up
use std::collections::HashMap;
 
fn main() {
let mut facts: HashMap<String, String> = HashMap::new();
facts.insert(String::from("pizza"), String::from("pepperoni please"));
facts.insert(String::from("dog"), String::from("woof"));
println!("{:?}", facts.get("pizza"));
println!("{:?}", facts.get("cat"));
}
$ cargo run
Some("pepperoni please")
None

get 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?

PredictSame key, twice
use std::collections::HashMap;
 
fn main() {
let mut facts: HashMap<String, String> = HashMap::new();
facts.insert(String::from("pizza"), String::from("pepperoni"));
facts.insert(String::from("pizza"), String::from("extra cheese"));
println!("{:?}", facts.get("pizza"));
}

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 loop let 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, or None for a bare /recall. Usage(String) carries the right way to type a command, for when /remember is missing a part.
  • In parse, /remember uses arg (lesson 5.4) twice. On /remember pizza pepperoni please, the first arg gives pizza pepperoni please; the name is its first_word, and a second arg gives the fact, pepperoni please. If either part is missing, the answer is Usage.
  • The Remember arm prints "got it" first and only then calls facts.insert(key, fact). The order matters: insert moves both Strings into the map, and after that they are not yours to print.
  • Recall(Some(key)) asks facts.get(&key) (the & lends the name to get, 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). Then names.sort(), and names.join(", ") glues the names into one piece of text with a comma between each.
Chatterbox v0.6 after lesson 6.3: the whole program (green lines are new in this lesson)
You type
Sam
/remember pizza pepperoni please
/recall pizza
/recall cat
/remember dog woof
/recall
/quit
Chatterbox prints (a real run)
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)
src/main.rs36 new lines
// Chatterbox: a small chat program, built one lesson at a time.
use std::collections::HashMap;
use std::io;
 
/// What the bot is called. A constant: fixed for the whole program.
const BOT: &str = "Chatterbox";
/// The version as a pair of numbers: (major, minor).
const VERSION: (u32, u32) = (0, 6);
/// The longest message we accept, in bytes.
const MAX_LEN: usize = 200;
/// What /help prints.
const HELP: &str = "commands: /help, /again, /history, /count, /remember <name> <fact>, /recall <name>, /say <text>, /shout <text>, /debug <text>, /quit (or /h, /q, /exit)";
 
/// One line of the conversation: who said it, and what they said.
struct Message {
author: String,
text: String,
}
 
impl Message {
/// Make a Message from two pieces of borrowed text.
fn new(author: &str, text: &str) -> Message {
Message {
author: String::from(author),
text: String::from(text),
}
}
 
/// The message as one transcript line: "you: hello".
fn to_line(&self) -> String {
format!("{}: {}", self.author, self.text)
}
 
/// The text in capitals, for /shout.
fn shout(&self) -> String {
self.text.to_uppercase()
}
}
 
/// Everything a line of input can mean. One enum, so a `match` on it must
/// handle every kind of line: the compiler checks that nothing is forgotten.
#[derive(Debug)]
enum Command {
Empty,
Help,
Quit,
Again,
History,
Count,
Remember(String, String),
Recall(Option<String>),
Usage(String),
Say(Option<String>),
Shout(Option<String>),
Unknown(String),
Debug(Option<String>),
Chat(String),
}
 
/// A borrowed Option<&str> turned into an owned Option<String>, so the
/// Command can keep the text after `line` is gone.
fn owned(text: Option<&str>) -> Option<String> {
match text {
Some(t) => Some(String::from(t)),
None => None,
}
}
 
/// Turn one line of input into a Command.
fn parse(line: &str) -> Command {
match first_word(line) {
"" => Command::Empty,
"/help" | "/h" => Command::Help,
"/quit" | "/q" | "/exit" => Command::Quit,
"/again" => Command::Again,
"/history" => Command::History,
"/count" => Command::Count,
"/remember" => match arg(line) {
Some(rest) => match arg(rest) {
Some(fact) => Command::Remember(String::from(first_word(rest)), String::from(fact)),
None => Command::Usage(String::from("/remember <name> <fact>")),
},
None => Command::Usage(String::from("/remember <name> <fact>")),
},
"/recall" => Command::Recall(owned(arg(line))),
"/debug" => Command::Debug(owned(arg(line))),
"/say" => Command::Say(owned(arg(line))),
"/shout" => Command::Shout(owned(arg(line))),
word => {
if is_command(word) {
Command::Unknown(String::from(word))
} else {
Command::Chat(String::from(line))
}
}
}
}
 
/// The first line Chatterbox prints.
fn banner() -> String {
format!("{} v{}.{}", BOT, VERSION.0, VERSION.1)
}
 
/// The greeting, with a name filled in.
fn greeting(name: &str) -> String {
let mut text = format!("Hi {}! I'm {}.", name, BOT);
text.push_str(" Ask me anything.");
text
}
 
/// True when the text is a command: it starts with a slash.
fn is_command(text: &str) -> bool {
text.starts_with('/')
}
 
/// The first word of the text: a slice (&str) pointing into it, not a copy.
fn first_word(text: &str) -> &str {
match text.find(' ') {
Some(i) => &text[..i],
None => text,
}
}
 
/// The text after the command word, if there is any: Some("hello") for
/// "/say hello", None for a bare "/say". No more "" standing in for nothing.
fn arg(line: &str) -> Option<&str> {
match line.find(' ') {
Some(i) => {
let rest = line[i + 1..].trim();
if rest.is_empty() { None } else { Some(rest) }
}
None => None,
}
}
 
/// What the bot says back to an ordinary message (not a command).
fn reply(message: &str) -> String {
if message.len() > MAX_LEN {
format!("that is too long (the limit is {} bytes)", MAX_LEN)
} else if message.ends_with('?') {
String::from("Good question! I can only echo for now. Ask me again in chapter 9.")
} else {
format!("you said: {}", message)
}
}
 
fn main() {
let mut messages_seen: u32 = 0;
let quiet = false;
let mut last: Option<String> = None; // the last thing you said, for /again
let mut history: Vec<Message> = Vec::new(); // everything said so far, in order
let mut facts: HashMap<String, String> = HashMap::new(); // name -> fact, for /recall
 
println!("{}", banner());
println!("What should I call you?");
let mut name_line = String::new();
io::stdin().read_line(&mut name_line).unwrap();
let name = name_line.trim();
if !quiet {
println!("{}", greeting(name));
}
 
let mut line = String::new();
loop {
line.clear();
let bytes = io::stdin().read_line(&mut line).unwrap();
if bytes == 0 {
break; // no more input: the keyboard was closed
}
let message = line.trim();
match parse(message) {
Command::Empty => {} // nothing typed: nothing to answer
Command::Quit => {
println!("bot: bye, {}!", name);
break;
}
Command::Help => println!("bot: {}", HELP),
Command::Again => {
if let Some(text) = &last {
println!("bot: {}", reply(text));
} else {
println!("bot: nothing to repeat yet");
}
}
Command::History => {
if history.is_empty() {
println!("bot: nothing said yet");
} else {
for (i, m) in history.iter().enumerate() {
println!("{}. {}", i + 1, m.to_line());
}
}
}
Command::Count => {
let mut bytes = 0;
for m in &history {
bytes += m.text.len();
}
println!("bot: {} messages, {} bytes of text", history.len(), bytes);
}
Command::Remember(key, fact) => {
println!("bot: got it: {} is {}", key, fact);
facts.insert(key, fact);
}
Command::Recall(Some(key)) => match facts.get(&key) {
Some(fact) => println!("bot: {} is {}", key, fact),
None => println!("bot: I don't know anything about {}", key),
},
Command::Recall(None) => {
if facts.is_empty() {
println!("bot: I don't remember anything yet. Try /remember");
} else {
// A HashMap has no order, so sort the names before printing them.
let mut names = Vec::new();
for name in facts.keys() {
names.push(name.as_str());
}
names.sort();
println!("bot: I remember: {}", names.join(", "));
}
}
Command::Usage(form) => println!("bot: try {}", form),
Command::Say(Some(text)) => println!("bot: {}", text),
Command::Say(None) => println!("bot: say what? Try /say hello"),
Command::Shout(Some(text)) => println!("bot: {}", Message::new("you", &text).shout()),
Command::Shout(None) => println!("bot: shout what? Try /shout hello"),
Command::Unknown(word) => {
println!("bot: I don't know the command {}. Try /help.", word)
}
Command::Debug(Some(text)) => println!("bot: {:?}", parse(&text)),
Command::Debug(None) => println!("bot: debug what? Try /debug /say hi"),
Command::Chat(text) => {
messages_seen += 1;
let said = Message::new("you", &text);
let answer = Message::new("bot", &reply(&said.text));
println!("bot: {}", answer.text);
history.push(said);
history.push(answer);
// Message::new made the history its own copy, so `text` itself can
// be handed to `last` for /again: no extra copy needed.
last = Some(text);
}
}
}
println!("messages so far: {}", messages_seen);
}

Download this version (zip)Unzip, then cargo run inside the folder.

Try itYour turn: read /remember in Chatterbox

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.

// Chatterbox: a small chat program, built one lesson at a time.
use std::collections::HashMap;
use std::io;
 
/// What the bot is called. A constant: fixed for the whole program.
const BOT: &str = "Chatterbox";
/// The version as a pair of numbers: (major, minor).
const VERSION: (u32, u32) = (0, 6);
/// The longest message we accept, in bytes.
const MAX_LEN: usize = 200;
/// What /help prints.
const HELP: &str = "commands: /help, /again, /history, /count, /remember <name> <fact>, /recall <name>, /say <text>, /shout <text>, /debug <text>, /quit (or /h, /q, /exit)";
 
/// One line of the conversation: who said it, and what they said.
struct Message {
author: String,
text: String,
}
 
impl Message {
/// Make a Message from two pieces of borrowed text.
fn new(author: &str, text: &str) -> Message {
Message {
author: String::from(author),
text: String::from(text),
}
}
 
/// The message as one transcript line: "you: hello".
fn to_line(&self) -> String {
format!("{}: {}", self.author, self.text)
}
 
/// The text in capitals, for /shout.
fn shout(&self) -> String {
self.text.to_uppercase()
}
}
 
/// Everything a line of input can mean. One enum, so a `match` on it must
/// handle every kind of line: the compiler checks that nothing is forgotten.
#[derive(Debug)]
enum Command {
Empty,
Help,
Quit,
Again,
History,
Count,
Remember(String, String),
Recall(Option<String>),
Usage(String),
Say(Option<String>),
Shout(Option<String>),
Unknown(String),
Debug(Option<String>),
Chat(String),
}
 
/// A borrowed Option<&str> turned into an owned Option<String>, so the
/// Command can keep the text after `line` is gone.
fn owned(text: Option<&str>) -> Option<String> {
match text {
Some(t) => Some(String::from(t)),
None => None,
}
}
 
/// Turn one line of input into a Command.
fn parse(line: &str) -> Command {
match first_word(line) {
"" => Command::Empty,
"/help" | "/h" => Command::Help,
"/quit" | "/q" | "/exit" => Command::Quit,
"/again" => Command::Again,
"/history" => Command::History,
"/count" => Command::Count,
// Remember(name, fact), or Usage("/remember <name> <fact>") when a part is missing
"/remember" => todo!(),
"/recall" => Command::Recall(owned(arg(line))),
"/debug" => Command::Debug(owned(arg(line))),
"/say" => Command::Say(owned(arg(line))),
"/shout" => Command::Shout(owned(arg(line))),
word => {
if is_command(word) {
Command::Unknown(String::from(word))
} else {
Command::Chat(String::from(line))
}
}
}
}
 
/// The first line Chatterbox prints.
fn banner() -> String {
format!("{} v{}.{}", BOT, VERSION.0, VERSION.1)
}
 
/// The greeting, with a name filled in.
fn greeting(name: &str) -> String {
let mut text = format!("Hi {}! I'm {}.", name, BOT);
text.push_str(" Ask me anything.");
text
}
 
/// True when the text is a command: it starts with a slash.
fn is_command(text: &str) -> bool {
text.starts_with('/')
}
 
/// The first word of the text: a slice (&str) pointing into it, not a copy.
fn first_word(text: &str) -> &str {
match text.find(' ') {
Some(i) => &text[..i],
None => text,
}
}
 
/// The text after the command word, if there is any: Some("hello") for
/// "/say hello", None for a bare "/say". No more "" standing in for nothing.
fn arg(line: &str) -> Option<&str> {
match line.find(' ') {
Some(i) => {
let rest = line[i + 1..].trim();
if rest.is_empty() { None } else { Some(rest) }
}
None => None,
}
}
 
/// What the bot says back to an ordinary message (not a command).
fn reply(message: &str) -> String {
if message.len() > MAX_LEN {
format!("that is too long (the limit is {} bytes)", MAX_LEN)
} else if message.ends_with('?') {
String::from("Good question! I can only echo for now. Ask me again in chapter 9.")
} else {
format!("you said: {}", message)
}
}
 
fn main() {
let mut messages_seen: u32 = 0;
let quiet = false;
let mut last: Option<String> = None; // the last thing you said, for /again
let mut history: Vec<Message> = Vec::new(); // everything said so far, in order
let mut facts: HashMap<String, String> = HashMap::new(); // name -> fact, for /recall
 
println!("{}", banner());
println!("What should I call you?");
let mut name_line = String::new();
io::stdin().read_line(&mut name_line).unwrap();
let name = name_line.trim();
if !quiet {
println!("{}", greeting(name));
}
 
let mut line = String::new();
loop {
line.clear();
let bytes = io::stdin().read_line(&mut line).unwrap();
if bytes == 0 {
break; // no more input: the keyboard was closed
}
let message = line.trim();
match parse(message) {
Command::Empty => {} // nothing typed: nothing to answer
Command::Quit => {
println!("bot: bye, {}!", name);
break;
}
Command::Help => println!("bot: {}", HELP),
Command::Again => {
if let Some(text) = &last {
println!("bot: {}", reply(text));
} else {
println!("bot: nothing to repeat yet");
}
}
Command::History => {
if history.is_empty() {
println!("bot: nothing said yet");
} else {
for (i, m) in history.iter().enumerate() {
println!("{}. {}", i + 1, m.to_line());
}
}
}
Command::Count => {
let mut bytes = 0;
for m in &history {
bytes += m.text.len();
}
println!("bot: {} messages, {} bytes of text", history.len(), bytes);
}
Command::Remember(key, fact) => {
println!("bot: got it: {} is {}", key, fact);
facts.insert(key, fact);
}
Command::Recall(Some(key)) => match facts.get(&key) {
Some(fact) => println!("bot: {} is {}", key, fact),
None => println!("bot: I don't know anything about {}", key),
},
Command::Recall(None) => {
if facts.is_empty() {
println!("bot: I don't remember anything yet. Try /remember");
} else {
// A HashMap has no order, so sort the names before printing them.
let mut names = Vec::new();
for name in facts.keys() {
names.push(name.as_str());
}
names.sort();
println!("bot: I remember: {}", names.join(", "));
}
}
Command::Usage(form) => println!("bot: try {}", form),
Command::Say(Some(text)) => println!("bot: {}", text),
Command::Say(None) => println!("bot: say what? Try /say hello"),
Command::Shout(Some(text)) => println!("bot: {}", Message::new("you", &text).shout()),
Command::Shout(None) => println!("bot: shout what? Try /shout hello"),
Command::Unknown(word) => {
println!("bot: I don't know the command {}. Try /help.", word)
}
Command::Debug(Some(text)) => println!("bot: {:?}", parse(&text)),
Command::Debug(None) => println!("bot: debug what? Try /debug /say hi"),
Command::Chat(text) => {
messages_seen += 1;
let said = Message::new("you", &text);
let answer = Message::new("bot", &reply(&said.text));
println!("bot: {}", answer.text);
history.push(said);
history.push(answer);
// Message::new made the history its own copy, so `text` itself can
// be handed to `last` for /again: no extra copy needed.
last = Some(text);
}
}
}
println!("messages so far: {}", messages_seen);
}

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.

One line counts every command typed
use std::collections::HashMap;
 
fn main() {
let mut counts: HashMap<String, u32> = HashMap::new();
for word in ["/help", "/say", "/help", "/help"] {
*counts.entry(String::from(word)).or_insert(0) += 1;
}
println!("/help typed {} times", counts["/help"]);
println!("/say typed {} times", counts["/say"]);
}
$ cargo run
/help typed 3 times
/say typed 1 times
If 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.

Try itPractice: count with a map

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.

use std::collections::HashMap;
 
struct Message {
author: String,
text: String,
}
 
impl Message {
fn new(author: &str, text: &str) -> Message {
Message { author: author.to_string(), text: text.to_string() }
}
}
 
fn count_by_author(history: &[Message]) -> HashMap<String, u32> {
// one row per author, value = how many messages
HashMap::new()
}
 
fn main() {
let history = vec![Message::new("sam", "a"), Message::new("ada", "b"), Message::new("sam", "c")];
let counts = count_by_author(&history);
println!("sam: {:?}", counts.get("sam"));
}

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.

Self-check

Say it out loud, then reveal

Self-checkRetrieval beats re-reading
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
A HashMap has no stable order, so to print in a predictable order you put the keys into a Vec and sort it.
What does <code>*counts.entry(key).or_insert(0) += 1</code> do?Reveal
It finds the row for the key, creates it with 0 if it does not exist, and adds one to the number stored in the map.

That is lesson 6.3. Tick it off so the course remembers where you are.

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.

Learn Rust by building a chat app · Lesson 6.3 · every compiler message above is real output from rustc 1.99.0 (b940084d7 2026-09-28) (edition 2024) · Vibe Engines · 2026