You cannot, safely. This is a limitation of the current entry API, and there’s no great solution. The anticipated solution is the “raw” entry API. See Stargateur’s answer for an example of using it.
The only stable solution using the Entry API is to always clone the key:
map.entry(key.clone()).or_insert(some_value);
Outside of the Entry API, you can check if the map contains a value and insert it if not:
if !map.contains_key(&key) {
map.insert(key.clone(), some_value);
}
map.get(&key).expect("This is impossible as we just inserted a value");
See also:
- [Pre-RFC] Abandonning Morals In The Name Of Performance: The Raw Entry API
- WIP: add raw_entry API to HashMap (50821)
- Extend entry API to work on borrowed keys. (1769)
- Add HashMap.entry_or_clone() method (1203)
For non-entry
based solutions, see: