HashMap entry must exist method (feature request)

Perhaps a bit of a niche feature request but consider this code:

if !map.contains_key(&x) {
     //some code which diverges
}

// some more stuff which doesn't mutate 'map'

*m.entry(x).or_default() += 1;

My problem with this is that we should never encounter a situation where the entry does not exist. I would prefer if there were a method like this:

if !map.contains_key(&x) {
     //some code which diverges
}

// some more stuff which doesn't mutate 'map'

*m.entry(x).must_exist() += 1;

where the .must_exist() method will panic if the entry does not exist (or maybe returns a Result).
I think this would be more useful for a programmer since the .or_default() method and the similar ones can hide potential bugs. Also, the .or_default() is a bit unclear if used in a bit of code where adding new keys to the hashmap doesn't make sense.

*m.get_mut(&x).unwrap() += 1;

lmao i'm an idiot nvm

If you don't need either exclusive or shared access to the map in between, you can also avoid the unwrap by keeping a proof that the mapping exists:

let Occupied(mut e) = map.entry("foo") else {
    // diverge
};

// ... stuff that does not touch map ...

*e.get_mut() += 1; // cannot fail!
10 Likes