Vectors, HashMaps and HashSets
Arrays have a fixed length, but the library does not: books arrive, get returned, and new members join every day. For data that grows, Rust's standard library gives you three workhorses. Choosing the right one is most of the job.
The rule
Order →
Vec; lookup by key →HashMap; no duplicates →HashSet.
Vec<T>: a growable list of one type, in order.
let mut returned: Vec<String> = Vec::new();
returned.push(String::from("Iron Tides"));
let also = vec![3, 1, 4]; // the vec! macro
let first = &returned[0]; // panics if empty
let maybe = returned.get(5); // None, no panicHashMap<K, V>: keys linked to values, looked up quickly by key.
use std::collections::HashMap;
let mut copies: HashMap<String, u32> = HashMap::new();
copies.insert(String::from("Iron Tides"), 3);
*copies.entry(String::from("Night Garden")).or_insert(0) += 1;
match copies.get("Iron Tides") {
Some(n) => println!("{n} copies"),
None => println!("not stocked"),
}insert on an existing key replaces its value. entry(...).or_insert(0) means "the value if it exists, otherwise start it at 0", which is the standard way to count things. A HashMap has no stable order: never rely on the order you iterate it in.
HashSet<T>: unique values only. Inserting a value that is already there changes nothing, and insert returns false to tell you.
use std::collections::HashSet;
let mut borrowers: HashSet<u32> = HashSet::new();
borrowers.insert(1042);
borrowers.insert(1042); // ignored, returns false
println!("{}", borrowers.len()); // 1HashMap and HashSet need use std::collections::...; Vec is always in scope.
The shortcut
Describe the data out loud and listen for the key word: "in order" → Vec, "for each X, the Y" → HashMap, "which ones, once each" → HashSet.
Say it
"For each title, the number of loans." That is "for each X, the Y": a
HashMap<String, u32>.
The trap is map["key"] or vec[i] on data that might be missing. Both panic; get returns an Option you can handle.
Drills
Answer fast — trust the rule.
Which collection fits "the titles returned today, in the order they came back"?
What does borrowers.len() print after inserting 1042 twice into a HashSet<u32>?
What does copies.get("Missing Book") return when the key is absent?
A map has "Iron Tides" => 3. What does copies.insert(String::from("Iron Tides"), 5) do?
Remember
Veckeeps order and grows;HashMapfinds by key;HashSetkeeps each value once.- Listen for "in order", "for each X, the Y", "once each".
- Trap: indexing can panic and hash collections have no order; use
get, and sort aVecwhen order matters.
