How to lookup from and insert into a HashMap efficiently?

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();

Leave a Comment