Sub topic 10
How HashMap takes ownership of keys and values
This chapter assumes you know Rust's move semantics, & and &mut references, Option and match, and the basic HashMap calls insert, get and remove. Here you will learn who owns the data after each of those calls, and why the compiler sometimes rejects code that looks harmless.
A HashMap owns what it stores
A HashMap<K, V> stores owned keys and values. Passing a value to insert moves it into the map, so the map becomes responsible for dropping it. When the map is dropped, every key and value it holds is dropped too.
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);
// println!("{key}"); // error[E0382]: borrow of moved value: `key`
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)
println!("{}", map.len()); // 1
}String is not Copy, so key and value are moved. i32 is Copy, so n is copied and stays usable. The string literal "seven" is a &'static str, which is also Copy.
Keeping your own copy
If you still need the value after inserting it, you have three options:
- Clone it before inserting.
- Insert a reference instead of an owned value.
- Read it back from the map later with
get.
Cloning is the simplest option and is correct whenever the copy cost is acceptable.
use std::collections::HashMap;
fn main() {
let name = String::from("Ana");
let mut ages: HashMap<String, u32> = HashMap::new();
ages.insert(name.clone(), 30);
println!("{name} {:?}", ages.get(&name)); // Ana Some(30)
}Maps that hold references
A map can store references, such as HashMap<&str, usize>. The map then owns the references, not the data they point to. The data must outlive the map, and the borrow checker enforces this.
use std::collections::HashMap;
fn main() {
let words = vec![String::from("alpha"), String::from("beta")];
let mut lengths: HashMap<&str, usize> = HashMap::new();
for w in &words {
lengths.insert(w.as_str(), w.len());
}
println!("{:?}", lengths.get("alpha")); // Some(5)
println!("{:?}", lengths.get("beta")); // Some(4)
// drop(words); // error[E0505]: cannot move out of `words`
// // because it is borrowed (while `lengths` is still used)
}This approach avoids allocating a new String per key. The cost is that the map is tied to the lifetime of words. You can't return lengths from a function that owns words locally. In that case, use owned String keys instead.
Lookups borrow, they do not move
get, contains_key and remove take a reference to the key, not the key itself. Their signature is generic: you can pass a &Q for any Q where the map's key type implements Borrow<Q>.
StringimplementsBorrow<str>, so aHashMap<String, V>can be queried with a&str.Vec<T>implementsBorrow<[T]>, so aHashMap<Vec<T>, V>can be queried with a slice.- Every type implements
Borrow<Self>, so passing&Stringalso works.
This is why stock.get("apple") works on a HashMap<String, u32> without building a temporary String. The Borrow contract requires that Q hashes and compares the same way as K. str and String do, so the lookup finds the entry.
What `insert` does with an existing key
insert returns Option<V>. If the key was absent, it returns None. If the key was present, it replaces the value and returns the old value, now owned by the caller.
The key you pass in on the second call is not stored. The map keeps the original key object and drops the new one. For String this makes no visible difference. It matters only for key types where two values compare equal but are not identical, such as a key type that compares case-insensitively.
use std::collections::HashMap;
fn main() {
let mut notes: HashMap<u32, String> = HashMap::new();
let first = notes.insert(1, String::from("draft"));
let second = notes.insert(1, String::from("final"));
println!("{:?}", first); // None
println!("{:?}", second); // Some("draft")
println!("{:?}", notes.get(&1)); // Some("final")
}Ignoring the return value of insert drops the old value silently. That is fine for most code, but when the value owns something important, such as a file handle or a connection, use the return value.
Getting values back out
Which method you call decides whether you borrow or take ownership.
| Method | Returns | Effect on the map |
|---|---|---|
| `get(&k)` | `Option<&V>` | Borrows the map immutably |
| `get_mut(&k)` | `Option<&mut V>` | Borrows the map mutably |
| `remove(&k)` | `Option<V>` | Takes the entry out, returns the owned value |
| `remove_entry(&k)` | `Option<(K, V)>` | Takes the entry out, returns the owned key and value |
Use get_mut to change a value in place. Use remove when you want to take ownership, for example to move a String out of the map without cloning it.
use std::collections::HashMap;
fn main() {
let mut inbox: HashMap<u32, String> = HashMap::new();
inbox.insert(1, String::from("hello"));
if let Some(msg) = inbox.get_mut(&1) {
msg.push_str(", world");
}
let owned: Option<String> = inbox.remove(&1);
println!("{:?} {}", owned, inbox.len()); // Some("hello, world") 0
}There is no way to get a &mut K for a key already in the map. Changing a key could change its hash, and the entry would then sit in the wrong bucket. To change a key, remove the entry with remove_entry and insert it again under the new key.
References into the map block changes to the map
get returns a reference into the map's storage. While that reference is alive, you cannot call insert or remove, because those may resize the table and move every entry. This is the same rule you saw with Vec.
use std::collections::HashMap;
fn main() {
let mut scores: HashMap<String, i32> = HashMap::new();
scores.insert(String::from("ana"), 10);
// This version does not compile:
// let first = scores.get("ana").unwrap(); // shared borrow starts
// scores.insert(String::from("bo"), 20); // error[E0502]
// println!("{first}"); // shared borrow still alive
// Copy the value out first. The borrow ends at the semicolon.
let first = *scores.get("ana").unwrap();
scores.insert(String::from("bo"), 20);
println!("{first} {}", scores.len()); // 10 2
}For a Copy value, dereference it. For a non-Copy value, call .clone() on it, or use remove if you no longer want it in the map.
Common mistakes
- Using a variable after
insertmoved it. Clone it first, or read it back withget. - Storing
&strkeys that point into aStringthat is dropped before the map. Use ownedStringkeys when the map outlives the source. - Calling
insertwhile holding a reference fromget. Copy or clone the value out first. - Expecting
insertto replace the key. Only the value is replaced. - Passing
&Stringwhere a&stris clearer. Both work, but&strlets callers use literals.
Exercise
This code does not compile. Name the error and give two different fixes. let title = String::from("Dune"); let mut years = std::collections::HashMap::new(); years.insert(title, 1965); println!("{title}");
Show answer
insert moved title into the map, so using it afterwards is a use of a moved value (E0382). Fix 1: insert a clone, years.insert(title.clone(), 1965);. Fix 2: do not print the local variable, and read the key back through the map instead, for example with years.get("Dune"). Making the map hold &str keys, years.insert(title.as_str(), 1965);, also works, as long as title outlives the map.
Exercise
A HashMap<String, Vec<u32>> named m contains the key "a". You need the Vec<u32> as an owned value, and you do not need the map to keep it. Which method should you call, and what does it return?
Show answer
Call m.remove("a"). It returns Option<Vec<u32>>, which is Some with the owned vector if the key was present and None otherwise. get would return only a reference, and you would need .clone() to own the data. remove avoids that copy because it moves the vector out of the map.