Skip to content
Theory · Collections · lesson 8 of 10

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:

Rust
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:

  1. use std::collections::HashMap; makes the name HashMap available. Vec and String are available right away, but HashMap needs this line above main.
  2. HashMap::new() creates an empty book. The compiler infers the key and value types from insert.
  3. insert("Anna", 1234) records a pair: the key "Anna" and the value 1234.
  4. get("Anna") looks up the value by its key and returns an Option: Some(1234) if the key exists, and None if it doesn't, as for "Vera".
  5. 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:

Rust
println!("{}", phones["Vera"]); // ✗
TEXT
no entry found for key

So 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:

Rust
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:

  1. text.split_whitespace() splits the text at the spaces and yields the words one by one.
  2. counts.entry(w) finds the place for the key w in the table, whether it is there or not.
  3. .or_insert(0) records 0 if the key was not there yet, and in any case returns a mutable reference &mut to the value inside the table.
  4. * stands before counts, but it applies to the result of the whole chain. The entry and or_insert calls run first, and then * follows the returned reference to the counter itself, like *n += 1 in the borrowing theme. += 1 adds 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:

Rust
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"]);
}
TEXT
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 line use std::collections::HashMap; makes its name available.
  • get returns Some(value) or None, while map[key] compiles and panics only when the key is missing.
  • *counts.entry(w).or_insert(0) += 1 counts: 0 is recorded only for a new key, and the reference is always returned.
  • The iteration order of a HashMap is undefined: never rely on it.