Reputation: 606
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
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
}
}
}
Upvotes: 4