4

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.

nalzok
  • 14,965
  • 21
  • 72
  • 139

1 Answers1

3

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.

nalzok
  • 14,965
  • 21
  • 72
  • 139
  • 1
    `HashMap` needs to own a `K` because keys can have the same hash and still need to be differentiated. – kmdreko Jun 28 '21 at 01:53
  • @kmdreko That makes sense! I think a `RefHashMap` which takes references to its keys and/or values can also be helpful when working with immutable structs which are costly to `clone`, though. – nalzok Jun 28 '21 at 01:57
  • 3
    you can do `HashMap<&Key, &Value>` if you want that – kmdreko Jun 28 '21 at 02:00
  • Also while it's probably a consequence of the hashmap storing the keys in order to resolve collisions, the hashmap does store keys and return (references to) them (e.g. default iterator, [`keys`](https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.keys), [`get_key_value`](https://doc.rust-lang.org/std/collections/struct.HashMap.html#method.get_key_value)). – Masklinn Jun 28 '21 at 05:39
  • @Masklinn That's true, but hashmaps can still return references to keys even if they don't take ownership of keys (e.g. by accepting a reference to the key in `insert`) – nalzok Jun 28 '21 at 05:42
  • @nalzok only by storing the reference, which is just a more complicated and less convenient way of storing the key. – Masklinn Jun 28 '21 at 05:43