Sub topic 9
Creating a HashMap and Inserting, Getting and Removing Entries
This chapter covers the core HashMap<K, V> operations: creating a map, inserting, reading, updating and removing entries. It assumes you know basic Rust syntax, ownership and borrowing (move, &, &mut), Option and match, and how to run programs with cargo. You should also have seen Vec<T> in the earlier chapters.
What a HashMap is
A HashMap<K, V> stores key-value pairs. You look up a value by its key, and on average the lookup takes constant time, no matter how many entries the map holds. Each key appears at most once. Inserting a key that already exists replaces its value.
HashMap is not in the prelude, so you import it:
use std::collections::HashMap;Three properties matter for everything below:
- Keys must be comparable and hashable (
EqandHash). A later chapter covers this in detail.String, integers,&str,bool,charand tuples of those all qualify. - Iteration order is unspecified. It can differ between runs.
- All keys share one type, and all values share one type.
Creating a map
HashMap::new makes an empty map. The compiler infers K and V from later use, or you can annotate them.
use std::collections::HashMap;
fn main() {
let mut stock: HashMap<String, u32> = HashMap::new();
println!("{} {}", stock.len(), stock.is_empty()); // 0 true
stock.insert(String::from("apple"), 3);
println!("{} {}", stock.len(), stock.is_empty()); // 1 false
}Maps are immutable by default like any other binding, so you need mut to insert or remove.
You can also build a map from an array of pairs with HashMap::from:
use std::collections::HashMap;
fn main() {
let prices = HashMap::from([("tea", 4), ("coffee", 3)]);
println!("{}", prices.len()); // 2
}Later chapters cover collect, which builds a map from any iterator of pairs. When you know roughly how many entries are coming, HashMap::with_capacity(n) avoids early resizing, much like Vec::with_capacity.
Inserting and replacing
insert(key, value) returns an Option<V>. It is None if the key was new, and Some(old_value) if the key already existed. In the second case the stored value is replaced, but the original key stays in the map.
use std::collections::HashMap;
fn main() {
let mut stock: HashMap<String, u32> = HashMap::new();
let first = stock.insert(String::from("apple"), 3);
println!("{:?}", first); // None
let old = stock.insert(String::from("apple"), 5);
println!("{:?}", old); // Some(3)
}Ignoring the return value is common. If you care whether you overwrote something, check it.
Getting values
get(&key) returns Option<&V>. It borrows the map and gives you a shared reference to the value, or None if the key is absent.
use std::collections::HashMap;
fn main() {
let mut stock: HashMap<String, u32> = HashMap::new();
stock.insert(String::from("apple"), 5);
match stock.get("apple") {
Some(n) => println!("apple: {n}"),
None => println!("no apples"),
}
let pears = stock.get("pear").copied().unwrap_or(0);
println!("pears: {pears}"); // pears: 0
}Two details are worth noting.
First, the map's key type is String, yet get("apple") takes a &str. This works because lookup methods are generic over a borrowed form of the key. If String: Borrow<str> holds, you can query with &str. You avoid allocating a String just to look something up. The Borrow contract requires that the borrowed form hashes and compares the same way as the owned form. String and str meet that requirement.
Second, get returns a reference. .copied() turns Option<&u32> into Option<u32> for Copy types. For non-Copy values such as String, use .cloned() or keep working with the reference.
Related read methods:
| Method | Returns | Use it to |
|---|---|---|
| `get(&k)` | `Option<&V>` | read a value |
| `get_mut(&k)` | `Option<&mut V>` | modify a value in place |
| `contains_key(&k)` | `bool` | test for presence only |
| `get_key_value(&k)` | `Option<(&K, &V)>` | read the stored key and value |
Indexing with map["apple"] also works, but it panics if the key is missing. Prefer get unless a missing key is a real bug. Indexing cannot be used for assignment either: map["apple"] = 1 does not compile, because HashMap implements Index but not IndexMut.
Updating in place with get_mut
To change a value without removing and re-inserting it, use get_mut:
use std::collections::HashMap;
fn main() {
let mut stock: HashMap<String, u32> = HashMap::new();
stock.insert(String::from("apple"), 5);
if let Some(n) = stock.get_mut("apple") {
*n += 10;
}
println!("{:?}", stock.get("apple")); // Some(15)
}The &mut u32 must be dereferenced with * to change the number. The mutable borrow of the map lasts as long as n is used. You cannot call other methods on stock while n is still live.
For "insert if missing, otherwise update" logic, the entry API is the better tool. It is the subject of a later chapter.
Removing entries
remove(&k) deletes the entry and returns Option<V>, which is the removed value or None. remove_entry(&k) returns Option<(K, V)> and hands back the stored key too. clear() removes everything but keeps the allocated capacity.
use std::collections::HashMap;
fn main() {
let mut stock: HashMap<String, u32> = HashMap::new();
stock.insert(String::from("apple"), 5);
stock.insert(String::from("plum"), 2);
println!("{:?}", stock.remove("apple")); // Some(5)
println!("{:?}", stock.remove("apple")); // None
println!("{}", stock.contains_key("plum")); // true
stock.clear();
println!("{}", stock.len()); // 0
}How the operations fit together
Every operation reports presence through an Option, so the compiler forces you to handle the missing-key case.
Common errors
- Forgetting
mut.insertandremoveneed&mut self. The compiler reports that you cannot borrow the map as mutable. - Passing the wrong reference type to
get.gettakes a reference to the key. With aHashMap<String, _>, bothget("x")andget(&owned_string)work.get(owned_string)does not. - Mismatched key types.
HashMap<&str, i32>queried with aStringfails. Pass&*sors.as_str()instead. - Indexing a missing key.
map["missing"]panics with no useful context. Useget. - Expecting order. Printing a map with
{:?}can show entries in a different order on each run. Sort the keys or use aBTreeMapwhen order matters. - Holding a reference across a mutation. A value from
getborrows the whole map. Inserting or removing while that reference is alive will not compile. Copy or clone the value first, or end the borrow before mutating.
A small worked example
This program tracks inventory using only the operations from this chapter. It is deterministic because it looks up specific keys instead of iterating.
use std::collections::HashMap;
fn main() {
let mut stock: HashMap<String, u32> = HashMap::new();
stock.insert("apple".to_string(), 10);
stock.insert("pear".to_string(), 4);
// Sell 3 apples, if we have enough.
if let Some(n) = stock.get_mut("apple") {
if *n >= 3 {
*n -= 3;
}
}
// Sell out of pears entirely.
let sold_pears = stock.remove("pear").unwrap_or(0);
println!("apples left: {:?}", stock.get("apple")); // Some(7)
println!("pears sold: {sold_pears}"); // 4
println!("pears now: {:?}", stock.get("pear")); // None
}Exercise
A HashMap<String, u32> named stock holds "apple" -> 5. What do these two lines print, in order? println!("{:?}", stock.insert("apple".to_string(), 9)); followed by println!("{:?}", stock.get("apple"));
Show answer
The first line prints Some(5), because insert returns the old value when the key already exists. The second prints Some(9), because get returns a reference to the new value wrapped in Some.
Exercise
Why does let n = stock.get("apple").unwrap(); stock.insert("plum".to_string(), 1); println!("{n}"); fail to compile, and how can you fix it?
Show answer
n is a &u32 that borrows the whole map, and it is still used after the insert, which needs a mutable borrow. Copy the value before inserting, for example let n = *stock.get("apple").unwrap();. The borrow then ends immediately.