Sub topic 9
Creating a HashMap and inserting, getting and removing entries
This chapter assumes you know basic Rust syntax, ownership and borrowing, Option and match, and how to run programs with cargo. It also assumes you have used Vec<T> from the earlier chapters.
A HashMap<K, V> stores values that you look up by key instead of by position. It lives in std::collections, so you must import it. Lookups, inserts and removals take constant time on average.
Creating a map
HashMap::new() creates an empty map. Rust infers the key and value types from later use, or you can write them out.
use std::collections::HashMap;
fn main() {
let mut stock: HashMap<String, u32> = HashMap::new();
println!("{}", stock.len()); // 0
stock.insert(String::from("pear"), 4);
println!("{}", stock.len()); // 1
}The map must be declared mut because inserting and removing change it.
Inserting, getting and removing
Three methods cover most everyday use:
| Method | Returns | Meaning |
|---|---|---|
| `insert(k, v)` | `Option<V>` | Stores the pair. Returns the old value if the key existed. |
| `get(&k)` | `Option<&V>` | Borrows the value for a key, if present. |
| `remove(&k)` | `Option<V>` | Takes the pair out and returns the value. |
use std::collections::HashMap;
fn main() {
let mut stock: HashMap<String, u32> = HashMap::new();
stock.insert(String::from("apple"), 3);
let old = stock.insert(String::from("apple"), 5);
println!("{:?}", old); // Some(3)
match stock.get("apple") {
Some(n) => println!("apple: {n}"),
None => println!("no apples"),
}
println!("{:?}", stock.remove("apple")); // Some(5)
println!("{:?}", stock.get("apple")); // None
}Inserting a second value under the same key replaces the first. That is why insert returns Some(3) the second time. If the key was new, it returns None.
What happens on a lookup
The map hashes the key to choose where to look, then compares keys with ==. This is why keys need Eq and Hash, which a later chapter covers.
Common mistakes
- Using
map[&key]for a key that may be missing. Indexing aHashMappanics if the key is absent, just like out-of-rangeVecindexing. Prefergetwhen absence is possible. - Passing the key by value to
get.gettakes a reference. Writestock.get("apple")orstock.get(&name), notstock.get(name). - Expecting an order. A
HashMapdoes not keep insertion order, and the order can change between runs. - Holding a
getresult while inserting. The returned&Vborrows the map, so a laterinsertis rejected until the reference is no longer used. This is the same rule that applies toVec::push.
Checking for a key
Use contains_key when you only need to know whether a key exists:
use std::collections::HashMap;
fn main() {
let mut ages: HashMap<&str, u8> = HashMap::new();
ages.insert("Ana", 30);
println!("{}", ages.contains_key("Ana")); // true
println!("{}", ages.contains_key("Bo")); // false
}Exercise
A map is HashMap<String, u32> and already holds ("apple", 3). You run let r = m.insert(String::from("apple"), 9);. What are r and the value now stored for "apple"?
Show answer
r is Some(3), the old value, and the map now stores 9 for "apple". insert replaces the value and returns the previous one wrapped in Some. It would return None if the key had not existed.
Exercise
Why does let n = stock["kiwi"]; risk a crash, and what would you write to handle a missing key safely?
Show answer
Indexing a HashMap panics when the key is absent. Use stock.get("kiwi") and handle the Option, for example with match or if let Some(n) = stock.get("kiwi").