HashMap and more about Option
A HashMap<K, V> stores key-value pairs and finds any value by its key very quickly, without walking the collection. It is the equivalent of Python dictionaries or JavaScript Map objects. You will need it to count words, store settings, group data or make indexes. In this lesson you will see how to use it, the entry pattern that avoids repeated code and how to work with the Options its queries return.
Create, insert and read
HashMap is not in the prelude, so you import it with use std::collections::HashMap. You insert with insert, which returns the previous value if the key already existed (as an Option). You read with get, which returns Option<&V>: Some(reference) or None. To delete you use remove. Keys must implement Eq and Hash, which integers, String, bool and tuples of them already do. Values that are String or Vec move into the map: the map becomes their owner. Careful: iteration order is not guaranteed; if you need order, use BTreeMap, which keeps the keys sorted.
use std::collections::HashMap;
fn main() {
let mut ages: HashMap<String, u32> = HashMap::new();
ages.insert(String::from("Ana"), 30);
ages.insert(String::from("Luis"), 25);
let old = ages.insert(String::from("Ana"), 31); // replaces
println!("previous: {:?}", old);
match ages.get("Luis") {
Some(age) => println!("Luis is {age}"),
None => println!("unknown"),
}
println!("{:?}", ages.get("Zoe"));
println!("has Ana? {}", ages.contains_key("Ana"));
ages.remove("Luis");
println!("{} entries", ages.len());
}The entry pattern
A very common problem is "if the key does not exist, create it with an initial value; if it exists, update it". That is what entry is for: map.entry(key) returns an object that represents the slot, and or_insert(value) returns a mutable reference to the value, creating it if needed. With that pattern, counting word frequency takes a single line inside the loop. Notice the asterisk: since or_insert returns &mut V, to add you must dereference with *.
use std::collections::HashMap;
fn main() {
let text = "the cat and the dog and the bird";
let mut counts: HashMap<&str, u32> = HashMap::new();
for word in text.split_whitespace() {
*counts.entry(word).or_insert(0) += 1;
}
// sort for a stable output
let mut pairs: Vec<(&&str, &u32)> = counts.iter().collect();
pairs.sort_by(|a, b| b.1.cmp(a.1).then(a.0.cmp(b.0)));
for (word, n) in pairs {
println!("{word}: {n}");
}
}Working with Option
Map queries return Option, and Option has many methods that save you a match. unwrap_or(value) gives a default if it is None; unwrap_or_default uses the default value of the type; map transforms the inner value if present; and_then chains another operation that also returns Option; is_some and is_none ask the state. Avoid unwrap() and expect() unless you are sure: if the value is None, the program panics. expect("message") at least explains why.
use std::collections::HashMap;
fn main() {
let mut stock: HashMap<&str, u32> = HashMap::new();
stock.insert("apple", 12);
stock.insert("pear", 0);
let apples = stock.get("apple").copied().unwrap_or(0);
let kiwis = stock.get("kiwi").copied().unwrap_or(0);
println!("{apples} {kiwis}");
let doubled = stock.get("apple").map(|n| n * 2);
println!("{:?}", doubled);
let label = match stock.get("pear") {
Some(0) => "sold out",
Some(_) => "available",
None => "not sold",
};
println!("{label}");
let words = vec!["10", "x", "30"];
let numbers: Vec<Option<i32>> = words.iter().map(|w| w.parse().ok()).collect();
println!("{:?}", numbers);
}Two practical details before the exercise. First, you can build a HashMap from a list of pairs with collect, which is handy for fixed tables. Second, when the value is a Vec, entry(key).or_default().push(x) adds an element, creating the empty list if needed; it is the standard pattern to group data by category. If you walk the map with for (key, value) in &map, you get references and the order may change between runs, so sort before printing when you need stable results, as we did with the word counter.
use std::collections::HashMap;
fn main() {
let mut letters: HashMap<char, u32> = HashMap::new();
for c in "hello world".chars().filter(|c| !c.is_whitespace()) {
*letters.entry(c).or_insert(0) += 1;
}
println!("o: {}", letters.get(&'o').copied().unwrap_or(0));
println!("z: {}", letters.get(&'z').copied().unwrap_or(0));
}Test what you learned
Question 1 of 4What does map.get(&key) return?
✎ My notes
Saved only in this browser. Sign in to keep it in your account.0/5000 characters