How can I update a value in a mutable HashMap?

Indexing immutably and indexing mutably are provided by two different traits: Index and IndexMut, respectively.

Currently, HashMap does not implement IndexMut, while Vec does.

The commit that removed HashMap‘s IndexMut implementation states:

This commit removes the IndexMut impls on HashMap and BTreeMap, in
order to future-proof the API against the eventual inclusion of an
IndexSet trait.

It’s my understanding that a hypothetical IndexSet trait would allow you to assign brand-new values to a HashMap, and not just read or mutate existing entries:

let mut my_map = HashMap::new();
my_map["key"] = "value";

For now, you can use get_mut:

*my_map.get_mut("a").unwrap() += 10;

Or the entry API:

*my_map.entry("a").or_insert(42) += 10;

Leave a Comment