A HashMap stores values under keys. Insert adds pairs and indexing reads a value back by key.

Program

Play the program to insert two scores and read one by name.

hashmap.rs
Replay: real traced execution (multi-file project)
use std::collections::HashMap;

fn main() {
    let mut scores = HashMap::new();
    scores.insert("Ada", 9);
    scores.insert("Lin", 12);
    let lin = scores["Lin"];
    println!("{lin}");
}
  1. scores ← {}, lin ← 12, scores["Lin"] ← 12

    3fn main() {4    let mut score→ {}s = HashMap::new();5    scores.insert("Ada", 9);6    scores.insert("Lin", 12);7    let li→ 12n = scores["Lin"→ 12];8    println!("{lin}");9}
    output12

Follow the Map

  1. scores starts as {}.
  2. Inserting Ada with 9 gives {Ada: 9}.
  3. Inserting Lin with 12 gives {Ada: 9, Lin: 12}.
  4. scores["Lin"] reads 12.
  5. The program prints 12. | moment | map state | read value | | --- | --- | --- | | start | {} | - | | after Ada | {Ada: 9} | - | | after Lin | {Ada: 9, Lin: 12} | Lin -> 12 |
HashMap::new `HashMap::new()` creates an empty map.
insert `insert(key, value)` stores a pair.
index `scores["Lin"]` reads the value for a known key.

Exercise: hashmap.rs

Reproduce the output 12, then identify which key is read from the map.