Rust Reference ยท Collections
Rust HashMap entry API
Reference for the Rust HashMap entry API: or_insert, or_insert_with, or_default, and_modify and matching on Entry::Occupied and Entry::Vacant.
map.entry(key) looks a key up once and gives you an Entry that represents either an occupied slot or a vacant one. You then decide what to do with it in a single expression, without hashing the key a second time and without fighting the borrow checker.
The classic use is counting and grouping: *counts.entry(word).or_insert(0) += 1. The methods or_insert, or_insert_with, or_default and and_modify return a mutable reference into the map (or the entry itself), so they chain nicely.
use std::collections::HashMap; let mut counts: HashMap<char, u32> = HashMap::new(); *counts.entry('a').or_insert(0) += 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 entry(&mut self, key: K) -> Entry<'_, K, V> impl<'a, K, V> Entry<'a, K, V> { pub fn or_insert(self, default: V) -> &'a mut V; pub fn or_insert_with<F: FnOnce() -> V>(self, default: F) -> &'a mut V; pub fn or_insert_with_key<F: FnOnce(&K) -> V>(self, default: F) -> &'a mut V; pub fn or_default(self) -> &'a mut V where V: Default; pub fn and_modify<F: FnOnce(&mut V)>(self, f: F) -> Entry<'a, K, V>; pub fn key(&self) -> &K; } pub enum Entry<'a, K, V> { Occupied(OccupiedEntry<'a, K, V>), Vacant(VacantEntry<'a, K, V>), }
| Name | Description |
|---|---|
key |
The key to look up. It is moved into the call, even if the slot turns out to be occupied. |
default |
Value (or closure producing it) used when the slot is vacant. |
f |
Closure applied to the existing value when the slot is occupied. |
Returns: the or_* methods return &mut V pointing at the value inside the map. and_modify returns the Entry so you can chain .or_insert(...).
Errors and panics: none. OccupiedEntry offers get, get_mut, into_mut, insert (returns the old value) and remove/remove_entry; VacantEntry offers insert, key and into_key.
Usage notes
- One hash, one lookup.
entryis the efficient replacement forif !map.contains_key(&k) { map.insert(k, v) }. or_insert(expensive())evaluates the argument eagerly, even if the key is present. Useor_insert_with(|| expensive())to run it only when needed.- The key is consumed.
entry(key)takes ownership. WithStringkeys you must build theStringeven for lookups of existing keys; if that matters, look up withget_mutfirst and fall back toentry. - The returned
&mut Vborrows the map. You cannot touch the map again until you are done with the reference. or_default()works withVec,String,HashMap, numbers (0) and anyDefaulttype, which makes grouping one-liners.- Grouping pattern:
map.entry(k).or_default().push(item). and_modify(...).or_insert(...)is the "upsert" idiom: update if present, create otherwise.BTreeMaphas the sameentryAPI instd::collections::btree_map.