Rust Reference ยท Collections
Rust HashMap insert, get and remove
Reference for the basic HashMap operations in Rust: insert, get, get_mut, remove, contains_key, try_insert alternatives and the Option results they return.
Three methods cover most of what you do with a HashMap<K, V>: insert adds or replaces a pair, get reads a value by key, and remove takes a pair out. All of them return Option values instead of failing, so a missing key is an ordinary case you handle with match, if let or the Option combinators.
Their companions are get_mut (a mutable reference to a value), get_key_value, remove_entry, contains_key, retain and clear.
let mut m = std::collections::HashMap::new(); let old = m.insert("k", 1); // None let v = m.get("k"); // Some(&1) let gone = m.remove("k"); // Some(1)
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
pub fn insert(&mut self, k: K, v: V) -> Option<V> pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V> pub fn get_mut<Q: ?Sized>(&mut self, k: &Q) -> Option<&mut V> pub fn get_key_value<Q: ?Sized>(&self, k: &Q) -> Option<(&K, &V)> pub fn contains_key<Q: ?Sized>(&self, k: &Q) -> bool pub fn remove<Q: ?Sized>(&mut self, k: &Q) -> Option<V> pub fn remove_entry<Q: ?Sized>(&mut self, k: &Q) -> Option<(K, V)> pub fn retain<F>(&mut self, f: F) where F: FnMut(&K, &mut V) -> bool
For the lookup methods, K: Borrow<Q> and Q: Hash + Eq.
| Name | Description |
|---|---|
k |
The key. For insert it is moved in; for lookups it is a reference to any borrowed form of the key. |
v |
The value to store. |
f |
retain calls it for every pair; return true to keep the pair. |
Returns: insert gives back the previous value (Some(old)) or None if the key was new. get and get_mut return None when the key is absent. remove returns the owned value.
Errors and panics: none of these panic (except on allocation failure). map[&k] indexing, in contrast, panics for a missing key.
Usage notes
inserton an existing key replaces the value but keeps the old key. If equal keys can differ in identity, the original key object stays in the map.- Borrowed lookups: pass
&strforStringkeys,&[T]forVec<T>keys. You never need to allocate aStringjust to ask a question. get(...).copied()or.cloned()turnsOption<&V>intoOption<V>forCopyorClonevalues.- Do not hold a
getreference while inserting. The borrow checker rejects it, and rightly: an insert may reallocate and move every value. - Check-then-insert is two lookups. Use the entry API when you want "insert if absent".
removedoes not shrink capacity. Callshrink_to_fitif memory matters.HashMap::try_insertis unstable; useentry(k)withEntry::Vacantto get the same effect on stable Rust.- All of these are O(1) on average and O(n) worst case when many keys collide.