Why does entry need the ownership of key?

Viewed 154

The declaration of entry is

pub fn entry(&mut self, key: K) -> Entry<'_, K, V>  // key is move into entry

whereas the one for get is

pub fn get<Q: ?Sized>(&self, k: &Q) -> Option<&V> where  // k is just a shared reference
    K: Borrow<Q>,
    Q: Hash + Eq, 

The Entry interface contains key and or_insert_with_key, but both methods merely call for a reference to key, so why does entry need the ownership of key while get doesn't?

In other words, what functionality does Entry offer by taking the ownership of key? If all it offers can be achieved with a shared reference, then I would say requiring ownership is unnecessary.

1 Answers

Well, I figured it out just after I posted the question: I missed insert

pub fn insert(&mut self, k: K, v: V) -> Option<V>

So methods like or_insert require ownership of key to call insert.


This brings us to another question: why does HashMap need the ownership of key? Since All it needs is the hash value of key, isn't a shared reference sufficient? I guess I should post a separate question to address that, though.

Related