Why is there no `OccupiedEntry::into_key`?

I can't see why there is no method to get back ownership of the key used to create the entry. There is such a method, into_key, for VacantEntry. OccupiedEntry will give you a reference to the key with key, and has an unstable method replace_key which moves the key into the map.

Is there a technical reason this can't exist? Has it just not been implemented / thought of yet? It would be useful right now for what seems like a fairly basic operation: checking if an entry exists, and inserting if it doesn't, returning Result<&mut V, (K, V)>. Is there any way to do this with just a single check of the map?

You can already do this with .entry(...).or_insert(...).

3 Likes

So something like this, but without having to lookup twice?

fn insert_without_consuming_key<K, V>(
    map: &mut HashMap<K, V>,
    key: K,
    value: V,
) -> Result<&mut V, (K, V)>
where
    K: Eq + Hash,
{
    if map.contains_key(&key) {
        Err((key, value))
    } else {
        Ok(map.entry(key).or_insert(value))
    }
}

Note that OccupiedEntry::key (currently) always gives you a reference to the existing key, not the replacement key. That said, with replace_key existing, I think the lack of an into_key is just and oversight; you (or someone else who cares) could try a PR to hashbrown (the library which std uses for the std hashmap) to add it.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.