Skip to lesson content
navan✳THE BUILD LABRUST
0/53 complete
BUILD LAB / RUST/ COLLECTIONS THAT WORK
BUILD NOTE 22 / 53

Look up by meaning.

Count and update keyed values without duplicate lookups.

BY NAVAN SAMI◷ 7 MIN READFOUNDATIONSRUST 2024

01 Understand the contract

HashMap<K, V> associates keys with values. insert takes ownership of owned keys and values; get borrows and returns Option<&V>. The entry API combines lookup with conditional insertion, which is useful for counters and caches. Iteration order is not a stable contract. Sort entries or use BTreeMap when deterministic key order is part of your output. Expected lookup is constant time under normal hashing assumptions, but hashing the key still costs work proportional to its representation.

02 Make it concrete

This is a complete standard-library example. Use Rust stable with the 2024 edition. Run it locally using the Rust workbench.

lessons/hash-maps/src/main.rs
use std::collections::HashMap;
fn main() {
    let mut counts = HashMap::new();
    for word in "build test build".split_whitespace() {
        *counts.entry(word).or_insert(0_u32) += 1;
    }
    println!("build={}", counts["build"]);
    println!("missing={:?}", counts.get("ship"));
}
↳ EXPECTED OUTPUT
build=2
missing=None
  1. 1

    entry gives access to an existing or inserted counter.

  2. 2

    The keys borrow the static text in this example.

  3. 3

    get is appropriate when the key may not exist.

From the extracted rust-workbench folder
cargo run -p lesson_hash_maps

03 Mind the boundary

04 Your next build

A SMALL MISSION

Count character frequencies and assert both a repeated and a missing character.

Reveal one possible solution +
solutions/hash-maps/src/main.rs
use std::collections::HashMap;
fn main() {
    let mut counts = HashMap::new();
    for ch in "banana".chars() {
        *counts.entry(ch).or_insert(0) += 1;
    }
    assert_eq!(counts.get(&'a'), Some(&3));
    assert_eq!(counts.get(&'x'), None);
}

05 Check your reasoning

QUICK SIGNAL CHECK

Does HashMap guarantee iteration in insertion order?

ONE MORE CONTRACT YOU CAN EXPLAIN.

Understand it.
Then make it yours.

Run the example, try your own input, and explain the boundary. Log the lesson when the idea makes sense.

Built with curiosity. By Navan Sami. ↗Rust · Make the contract clear. Then build.