Sub topic 3
Updating Values and Choosing Rust Collections
Assume you know ownership and borrowing, Option, iterators, and how to run a Cargo project. This chapter focuses on the HashMap entry API and how collection choices affect access patterns.
Updating values with the entry API
The entry API lets you inspect or create a value for a key in one lookup. or_insert returns a mutable reference to the existing value or inserts its argument when the key is absent.
use std::collections::HashMap;
fn main() {
let words = "red blue red green blue red";
let mut counts: HashMap<&str, usize> = HashMap::new();
for word in words.split_whitespace() {
*counts.entry(word).or_insert(0) += 1;
}
for (word, count) in &counts {
println!("{word}: {count}");
}
let mut groups: HashMap<usize, Vec<&str>> = HashMap::new();
for word in ["cat", "bird", "ox"] {
groups.entry(word.len()).or_default().push(word);
}
println!("{:?}", groups[&3]);
}Use or_default when the value type implements Default, such as Vec.
Iterating over a `HashMap`
map.keys()yields shared references to keys.map.values()yields shared references to values.map.iter()or&mapyields key-value pairs.map.values_mut()yields mutable references to values.
A HashMap does not promise iteration order. Sort collected pairs when output must be repeatable.
What makes a type usable as a key
A key must implement Eq and Hash. Equal keys must produce equal hashes. Derive both traits when every field supports them.
#[derive(Debug, PartialEq, Eq, Hash)]
struct Point {
x: i32,
y: i32,
}Do not mutate information that affects a key while the key is inside a map.
Building collections with `collect`
collect uses the expected type to choose a collection.
use std::collections::HashMap;
fn main() {
let names = vec!["Ana", "Bo"];
let ages = vec![30, 25];
let ages_by_name: HashMap<_, _> =
names.into_iter().zip(ages).collect();
let squares: Vec<u32> =
(1..=4).map(|n| n * n).collect();
println!("{:?}", ages_by_name);
println!("{squares:?}");
}Choosing a collection
| Collection | Best fit |
|---|---|
| `Vec<T>` | Ordered data and index-based access |
| `HashMap<K, V>` | Fast average lookup by key |
| `BTreeMap<K, V>` | Sorted keys and ordered range operations |
Exercise
Which API updates a word count without first checking whether the key exists?
Show answer
Use counts.entry(word).or_insert(0) and mutate the returned reference.