How to lookup from and insert into a HashMap efficiently?
The entry
API is designed for this. In manual form, it might look like
use std::collections::hash_map::Entry;
let values: &Vec<isize> = match map.entry(key) {
Entry::Occupied(o) => o.into_mut(),
Entry::Vacant(v) => v.insert(default)
};
Or one can use the briefer form:
map.entry(key).or_insert_with(|| default)
If default
is OK/cheap to compute even when it isn't inserted, it can also just be:
map.entry(key).or_insert(default)
I've used @huon and @Shepmaster's answer and just 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 somewhere else I can just do:
use crate::utils::hashmap::InsertOrGet;
let new_or_existing_value: &mut ValueType = my_map.insert_or_get(my_key.clone());