Alex Ozdemir
Alex Ozdemir

Reputation: 606

Can you insert into a HashMap in a way the gives you an owned copy of the key if an entry is present?

Rust's HashMap::insert takes (K, V) and returns an (owned) V if an entry was already present. In this case, there should also be an (owned) key in the existing entry. Is there a way to get it?

i.e. is there a way to implement something like HashMap::insert_entry(&mut self, k: K, v: V) -> Option(K, V)>?

I see that you could do HashMap::remove_entry followed by HashMap::insert, but this requires two lookups. I believe this should only require one.

Upvotes: 1

Views: 445

Answers (1)

apatniv
apatniv

Reputation: 1856

You can use HashMap::entry and its variants, along with the map_entry_replace feature:

#![feature(map_entry_replace)]

fn insert_entry<K: Hash + Eq, V>(m: &mut HashMap<K, V>, k: K, v: V) -> Option<(K, V)> {
    match m.entry(k) {
        Entry::Occupied(o) => {
            Some(o.replace_entry(v))
        }
        Entry::Vacant(va) => {
            va.insert(v);
            None
        }
    }
}

playground link

Upvotes: 4

Related Questions