TExcelTAD
Home › Rust › Rust HashMap

Rust HashMap

A HashMap stores data as key → value pairs. Instead of finding an item by its position (like v[3]), you find it by a key you choose — a name, an ID, a word. Looking up a key is fast no matter how many entries the map holds.

HashMap lives in the standard library's collections module, so you bring it into scope with use.

Creating a map and inserting pairs

rust · try it yourself
use std::collections::HashMap;

fn main() {
    let mut stock: HashMap<&str, u32> = HashMap::new();

    stock.insert("apples", 40);
    stock.insert("bananas", 12);
    stock.insert("cherries", 0);

    println!("We track {} products", stock.len());
    println!("Apples in stock: {}", stock["apples"]);
}
We track 3 products
Apples in stock: 40

All keys must have the same type, and all values must have the same type (they can differ from each other — here keys are &str and values are u32).

Reading values safely

map[key] panics if the key is missing. The safer get returns an Option<&V>:

rust · try it yourself
use std::collections::HashMap;

fn main() {
    let mut ages = HashMap::new();
    ages.insert("Tom", 31);
    ages.insert("Una", 27);

    for name in ["Tom", "Vic"] {
        match ages.get(name) {
            Some(age) => println!("{} is {} years old", name, age),
            None => println!("{} is not in the map", name),
        }
    }

    println!("Contains Una? {}", ages.contains_key("Una"));
}
Tom is 31 years old
Vic is not in the map
Contains Una? true

Updating and removing

Inserting with an existing key replaces the old value. remove deletes a pair and returns the value it held. The entry API lets you insert a value only when the key is new, or modify the existing one.

rust · try it yourself
use std::collections::HashMap;

fn main() {
    let mut points = HashMap::new();
    points.insert("red team", 10);
    points.insert("red team", 15); // overwrites 10

    points.entry("blue team").or_insert(0);   // added, was missing
    points.entry("red team").or_insert(100);  // ignored, already there

    *points.entry("blue team").or_insert(0) += 7;

    println!("red:  {}", points["red team"]);
    println!("blue: {}", points["blue team"]);

    let removed = points.remove("red team");
    println!("Removed: {:?}, left: {}", removed, points.len());
}
red:  15
blue: 7
Removed: Some(15), left: 1

or_insert returns a mutable reference to the value, so *... += 7 changes it in place.

Iterating — and why order is not guaranteed

You can loop over a map with for (key, value) in &map. But a HashMap does not keep any particular order, and the order can even differ between runs of the same program. If you need sorted output, collect the keys and sort them, or use a BTreeMap, which always keeps its keys sorted.

rust · try it yourself
use std::collections::{BTreeMap, HashMap};

fn main() {
    let text = "the cat and the dog and the bird";

    let mut counts: HashMap<&str, i32> = HashMap::new();
    for word in text.split_whitespace() {
        *counts.entry(word).or_insert(0) += 1;
    }

    // Option 1: sort the keys of a HashMap before printing
    let mut words: Vec<&&str> = counts.keys().collect();
    words.sort();
    for w in words {
        println!("{} -> {}", w, counts[*w]);
    }

    // Option 2: a BTreeMap is always sorted by key
    let sorted: BTreeMap<_, _> = counts.into_iter().collect();
    println!("{:?}", sorted);
}
and -> 2
bird -> 1
cat -> 1
dog -> 1
the -> 3
{"and": 2, "bird": 1, "cat": 1, "dog": 1, "the": 3}

This "count how often each thing appears" pattern with entry(...).or_insert(0) is one of the most common uses of a map.

Common methods

Method What it does
insert(k, v) add or replace a pair; returns the old value as Option
get(&k) Some(&v) or None
get_mut(&k) mutable access, Some(&mut v) or None
contains_key(&k) true if the key exists
remove(&k) delete the pair, returns Option<V>
entry(k).or_insert(v) get existing value or insert v
len() / is_empty() number of pairs / is it empty
keys() / values() iterate over keys or values only

Ownership of keys and values

When you insert an owned value such as a String, the map takes ownership of it:

rust
use std::collections::HashMap;

fn main() {
    let key = String::from("color");
    let mut settings = HashMap::new();
    settings.insert(key, "blue");
    println!("{}", key); // error: key was moved into the map
}
text
error[E0382]: borrow of moved value: `key`

Insert key.clone() if you still need the original, or use &str keys when the strings live long enough.

Note: For key types to work in a HashMap they must implement Eq and Hash. Strings, integers, char, bool and tuples of those all do. Floating-point numbers do not.

Test yourself

What does map.get("x") return if the key "x" does not exist?

  1. 0
  2. An empty string
  3. None
  4. It panics

Why might the output of looping over a HashMap differ between runs?

  1. HashMap iteration order is not specified
  2. HashMap removes random entries
  3. Rust shuffles every collection
  4. Keys are stored as random numbers

What happens when you insert a key that is already in the map?

  1. Compile error
  2. The new value replaces the old one
  3. Both values are kept
  4. The insert is ignored