HashMap entry must exist method (feature request)
⚓ Rust 📅 2025-11-19 👤 surdeus 👁️ 11Perhaps 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.
4 posts - 3 participants
🏷️ Rust_feed