HashMap and entry
Picture a phone book. You look up a number in it by the person's name, not by the line: you open the book at that name, and the number is right there. You don't have to leaf through the whole book.
A vector can't do that: you find an element in it by its number, and to find an entry by name you would have to go through every element. For lookup by key, Rust has HashMap:
use std::collections::HashMap;
fn main() {
let mut phones = HashMap::new();
phones.insert("Anna", 1234);
phones.insert("Boris", 5678);
println!("{:?}", phones.get("Anna")); // Some(1234)
println!("{:?}", phones.get("Vera")); // None
println!("{}", phones["Boris"]); // 5678
}Let's walk through the example line by line:
use std::collections::HashMap;makes the nameHashMapavailable.VecandStringare available right away, butHashMapneeds this line abovemain.HashMap::new()creates an empty book. The compiler infers the key and value types frominsert.insert("Anna", 1234)records a pair: the key"Anna"and the value1234.get("Anna")looks up the value by its key and returns anOption:Some(1234)if the key exists, andNoneif it doesn't, as for"Vera".phones["Boris"]returns the value itself, without a wrapper.
Key and value
A HashMap<K, V> is a table of key–value pairs: K is the key type, V is the value type. Keys in it never repeat: insert with a key it already knows replaces the old value with the new one. Lookup by key is fast however many pairs there are: from the key itself the table works out where its value lies, without going through the other pairs.
Here the phone book analogy falls short. In a book the names are in alphabetical order, but a HashMap has no order. A loop over it visits the pairs in an unpredictable order, which may change from run to run. So you never print the iteration order and never rely on it.
Reading by key
You can read a value in two ways, as with a vector's element.
The get method
get returns an Option, so a missing key is not an error but None. You take it when the key may be absent.
The index map[key]
phones["Boris"] compiles and returns the value. But if the key is missing, the program stops with a panic:
println!("{}", phones["Vera"]); // ✗no entry found for keySo you write the index only where the key surely exists.
Counting with entry
A classic task is to count how many times each word occurs. For each word you need to record 0 if the word is not in the book yet, and then add one to its counter. The entry method does this in one line:
use std::collections::HashMap;
fn main() {
let text = "red blue red green red blue";
let mut counts = HashMap::new();
for w in text.split_whitespace() {
*counts.entry(w).or_insert(0) += 1;
}
println!("{} {} {}", counts["red"], counts["blue"], counts["green"]); // 3 2 1
}Let's take the counting line apart:
text.split_whitespace()splits the text at the spaces and yields the words one by one.counts.entry(w)finds the place for the keywin the table, whether it is there or not..or_insert(0)records 0 if the key was not there yet, and in any case returns a mutable reference&mutto the value inside the table.*stands beforecounts, but it applies to the result of the whole chain. Theentryandor_insertcalls run first, and then*follows the returned reference to the counter itself, like*n += 1in the borrowing theme.+= 1adds one.
On the first red the key is not there yet: or_insert records 0 and hands back a reference to it at once, and the counter becomes 1. On the second red the key already exists: or_insert records nothing and hands back a reference to the current value. In the end red occurred three times, blue twice, and green once.
Interviewers ask you to write this idiom almost word for word: "Count the words with a HashMap."
Common mistake
The * before counts.entry(w) is forgotten:
use std::collections::HashMap;
fn main() {
let mut counts = HashMap::new();
for w in "red blue red".split_whitespace() {
counts.entry(w).or_insert(0) += 1; // ✗
}
println!("{}", counts["red"]);
}error[E0368]: binary assignment operation `+=` cannot be applied to type `&mut {integer}`The program does not compile. or_insert returns not a number but a &mut reference to it, and you can't add one to a reference. In the message, {integer} means "some integer" whose type the compiler has not pinned down yet. The fix is *counts.entry(w).or_insert(0) += 1.
Key points
HashMap<K, V>stores key–value pairs and finds a value by its key without a search; the lineuse std::collections::HashMap;makes its name available.getreturnsSome(value)orNone, whilemap[key]compiles and panics only when the key is missing.*counts.entry(w).or_insert(0) += 1counts: 0 is recorded only for a new key, and the reference is always returned.- The iteration order of a
HashMapis undefined: never rely on it.