Sub topic 10
How HashMap Takes Ownership of Keys and Values
This chapter assumes you know Rust's move semantics, the difference between & and &mut, and how to create a HashMap and call insert and get. It covers what happens to the values you put into a map and how to avoid the errors that follow.
Insertion moves owned values
A HashMap<K, V> owns its keys and values. When you call insert, the map takes the arguments by value. Types that own heap data, such as String and Vec, are moved into the map. Types that implement Copy, such as i32, are copied.
use std::collections::HashMap;
fn main() {
let key = String::from("color");
let value = String::from("green");
let mut map = HashMap::new();
map.insert(key, value);
// key and value were moved into the map and cannot be used here.
let n = 7;
let mut lengths = HashMap::new();
lengths.insert("seven", n); // i32 is Copy, so n is still usable
println!("{n} {:?}", lengths.get("seven")); // 7 Some(7)
}After map.insert(key, value), using key or value is a compile error: "borrow of moved value". The map now owns those strings. They are dropped when the map is dropped, or when the entry is removed or overwritten.
Inserting references
A map can hold references instead of owned values. Then the map does not own the data, and the referenced data must outlive the map.
use std::collections::HashMap;
fn main() {
let name = String::from("Ana");
let mut ages: HashMap<&str, u32> = HashMap::new();
ages.insert(&name, 30);
println!("{name} {:?}", ages.get("Ana")); // Ana Some(30)
}Here name is only borrowed, so it stays usable. The compiler enforces the lifetime. If name were dropped while ages was still in use, the program would not compile. Moving name into another variable while ages still holds the borrow would also fail.
Overwriting and the returned value
insert on an existing key replaces the value and returns the old one as Some(old). The old value is handed back to you, so it is not dropped inside the map. For a new key, insert returns None.
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)
}The key is a subtle case. When the key already exists, the map keeps its original key object and drops the new key you passed. Only the value is replaced.
Lookups borrow, removal moves out
get takes a reference to the key and returns Option<&V>. The reference borrows the map, so you cannot modify the map while you hold it. This is the same rule you saw for Vec.
HashMap<String, _> can be queried with a &str, so you do not need to build a String for each lookup. remove takes the entry out of the map and returns the value as Option<V>, so ownership passes back to you.
use std::collections::HashMap;
fn main() {
let mut stock: HashMap<String, u32> = HashMap::new();
stock.insert(String::from("pear"), 4);
if let Some(n) = stock.get("pear") {
println!("pear: {n}");
}
let taken = stock.remove("pear");
println!("{:?} {}", taken, stock.len()); // Some(4) 0
}Ownership flow
Common errors
- Using a variable after passing it to
insert. Clone it first or insert a reference. - Holding a
getreference while callinginsertorremove. Copy or clone the value out first. - Storing references to values that do not live as long as the map.
Exercise
The code let k = String::from("a"); let mut m = HashMap::new(); m.insert(k, 1); println!("{k}"); fails to compile. Why, and how can you fix it without removing the println!?
Show answer
insert takes k by value, so the String is moved into the map and k is no longer valid. Insert a copy with m.insert(k.clone(), 1);, or make the map hold a reference with HashMap<&String, i32> and m.insert(&k, 1);.