Learn HashMap in Rust

HashMap<K, V> stores pairs of a key (K, the name to search with) and a value (V, the data stored), and needs use std::collections::HashMap;. insert stores one…

How much is an iced tea? The cashier at Rusdi's Pancake Stall doesn't count rows on the price list to answer that. He looks for the words "iced tea" on the price list on the wall and finds $5, without caring which row iced tea is on. A Vec can't do that, because its items are found by position number.

To find things by name, Rust has HashMap<K, V>. A HashMap stores pairs of a key (type K) and a value (type V). The key is the name you search with, and the value is the data stored for that key. Below that price list hangs a tally sheet for counting orders per menu item. For each order, the cashier finds the item's row and adds one tick. An item ordered for the first time gets a new row starting at 0. On both sheets, the menu name is the key. The price on the price list, or the number of ticks on the tally sheet, is the value.

Making a HashMap, insert and get

This program makes a HashMap of menu prices, fills it with three items, then reads it:

use std::collections::HashMap;

fn main() {
    let mut menu_prices: HashMap<String, u32> = HashMap::new();
    menu_prices.insert(String::from("sweet pancake"), 32);
    menu_prices.insert(String::from("egg pancake"), 38);
    menu_prices.insert(String::from("iced tea"), 5);
    println!("Menu items: {}", menu_prices.len());
    println!("{:?}", menu_prices.get("iced tea"));
    println!("{:?}", menu_prices.get("coffee"));
    match menu_prices.get("egg pancake") {
        Some(price) => println!("Egg Pancake: {}", price),
        None => println!("Not on the menu"),
    }
    let old = menu_prices.insert(String::from("iced tea"), 6);
    println!("{:?} {}", old, menu_prices.len());
}

The output:

Menu items: 3
Some(5)
None
Egg Pancake: 38
Some(5) 3

Counting orders with entry().or_insert()

This program is that tally sheet: six orders come in, and the orders for each item are counted in the HashMap counts:

use std::collections::HashMap;

fn main() {
    let orders = ["sweet pancake", "iced tea", "sweet pancake", "egg pancake", "iced tea", "sweet pancake"];
    let mut counts: HashMap<&str, u32> = HashMap::new();
    for menu in orders {
        *counts.entry(menu).or_insert(0) += 1;
    }
    println!("sweet pancake: {}", counts["sweet pancake"]);
    println!("iced tea: {}", counts["iced tea"]);
    println!("egg pancake: {}", counts["egg pancake"]);
}

The output:

sweet pancake: 3
iced tea: 2
egg pancake: 1

This table shows what counts holds after each order:

Order The item's row counts afterwards
sweet pancake not there: made at 0, then +1 sweet 1
iced tea not there: made at 0, then +1 sweet 1, iced tea 1
sweet pancake already there: +1 sweet 2, iced tea 1
egg pancake not there: made at 0, then +1 sweet 2, iced tea 1, egg 1
iced tea already there: +1 sweet 2, iced tea 2, egg 1
sweet pancake already there: +1 sweet 3, iced tea 2, egg 1

The order can't be relied on

Put three menu items into menu_prices one after another: sweet pancake, egg pancake, then iced tea. Then print them all with for (menu, price) in &menu_prices. In what order will the lines print? Guess first, then look at the result. The program is built once with cargo build, then run twice with ./target/debug/stall:

$ ./target/debug/stall
sweet pancake: 32
iced tea: 5
egg pancake: 38
$ ./target/debug/stall
iced tea: 5
egg pancake: 38
sweet pancake: 32

The same program, a different order, and neither is the order of the inserts. So the order really can't be predicted. The reason is in how a HashMap stores pairs. A HashMap calculates a number from each key, called a hash, then uses that number to pick a drawer (a place in memory) to store the pair in. Someone could send keys on purpose that all land in the same drawer, to make the program slow. To stop that, Rust randomizes that hash formula every time the program runs (RandomState). As a result, the order of the drawers, and the order of for, can change from run to run.

BTreeMap when order matters

BTreeMap is used exactly like HashMap, but its items are always sorted by key. This program inserts the same three items in the same order:

use std::collections::BTreeMap;

fn main() {
    let mut menu_prices: BTreeMap<&str, u32> = BTreeMap::new();
    menu_prices.insert("sweet pancake", 32);
    menu_prices.insert("egg pancake", 38);
    menu_prices.insert("iced tea", 5);
    for (menu, price) in &menu_prices {
        println!("{}: {}", menu, price);
    }
    println!("{:?}", menu_prices);
}

The output:

egg pancake: 38
iced tea: 5
sweet pancake: 32
{"egg pancake": 38, "iced tea": 5, "sweet pancake": 32}

The order is alphabetical by key, the same on every run. Remember: sorted by key, not by the order of the inserts. Use a HashMap when you only need to find things by key (the most common case), and a BTreeMap when the result must print in order.

⚠️ Why is your HashMap refused, panicking, or printing in random order?

TL;DR: HashMap<K, V> stores pairs of a key (K, the name to search with) and a value (V, the data stored), and needs use std::collections::HashMap;. insert stores one pair, and replaces the old value when the key already exists. get gives Some(&value) when the key exists, or None when it doesn't. Reading with square brackets, map["key"], makes the program panic (stop) when the key is missing. To count, write *map.entry(key).or_insert(0) += 1: a new key gets the value 0, then * changes that value, adding 1. The for order of a HashMap can't be relied on, because its hash formula (how it picks a place for each key) is randomized on every run. Use a BTreeMap when the result must be sorted by key.

⚡ Look up by name, not by number

Write:

use std::collections::HashMap;

let mut menu_prices: HashMap<String, u32> = HashMap::new();
menu_prices.insert(String::from("iced tea"), 5);
println!("{:?}", menu_prices.get("iced tea"));

Meaning: HashMap<String, u32> stores pairs of a key and a value: the key is a menu name (String), the value a price (u32). insert stores one pair, and get finds a value by its key: it gives Some(5), or None when the key is missing. Unlike Vec, HashMap isn't loaded automatically. It is in std::collections, so the use line is required.

⚡ The tally sheet

Write:

for menu in orders {
    *counts.entry(menu).or_insert(0) += 1;
}

Meaning: This code counts the orders for each item, like ticks on a tally sheet. orders holds the names of the items ordered, and counts is a HashMap from an item's name to its number of orders. entry(menu).or_insert(0) makes a row worth 0 if that item isn't there yet, then hands over a borrow of its value. The * in front changes that borrowed value: add 1.

⚡ An order that keeps changing

Guess first: three menu items are put into a HashMap with insert, one after another, then printed with for. Is the printed order the same as the order of the inserts?

It can't be relied on. A HashMap picks the place for each pair from a number calculated from its key (its hash), and the formula for that number is randomized every time the program runs. So the for order can differ from one run to the next.

Meaning: When the result must be sorted by key, use a BTreeMap, which is used the same way as a HashMap.

What you will learn