How to lookup from and insert into a HashMap efficiently?
I've used huon's answer and implemented it as a trait:
use std::collections::HashMap;
use std::hash::Hash;
pub trait InsertOrGet<K: Eq + Hash, V: Default> {
fn insert_or_get(&mut self, item: K) -> &mut V;
}
impl<K: Eq + Hash, V: Default> InsertOrGet<K, V> for HashMap<K, V> {
fn insert_or_get(&mut self, item: K) -> &mut V {
return match self.entry(item) {
std::collections::hash_map::Entry::Occupied(o) => o.into_mut(),
std::collections::hash_map::Entry::Vacant(v) => v.insert(V::default()),
};
}
}
Then I can do:
use crate::utils::hashmap::InsertOrGet;
let new_or_existing_value: &mut ValueType = my_map.insert_or_get(my_key.clone());
The entry
API is designed for this. In manual form, it might look like
let values = match map.entry(key) {
Entry::Occupied(o) => o.into_mut(),
Entry::Vacant(v) => v.insert(default),
};
One can use the briefer form via Entry::or_insert_with
:
let values = map.entry(key).or_insert_with(|| default);
If default
is already computed, or if it's OK/cheap to compute even when it isn't inserted, you can use Entry::or_insert
:
let values = map.entry(key).or_insert(default);
If the HashMap
's value implements Default
, you can use Entry::or_default
, although you may need to provide some type hints:
let values = map.entry(key).or_default();