Collections
HashMap
Key to Value
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}");
}
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
scoresstarts as{}.- Inserting Ada with
9gives{Ada: 9}. - Inserting Lin with
12gives{Ada: 9, Lin: 12}. scores["Lin"]reads12.- 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.