How do I use the Entry API with an expensive key that is only constructed if the Entry is Vacant?

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:

For non-entry based solutions, see:

Leave a Comment