Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does HashMap::get and HashMap::entry take different types of key?

The signature of HashMap::entry is:

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

Ok, looks good. I want to take an entry from the HashMap whose key is K, so of course I need to give it a K.

However, the signature of HashMap:get is:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Now I’m utterly confused. What’s with this complicated constraint? Why isn’t it just K or &K?

>Solution :

When you use entry, you get either a vacant entry, or an occupied entry. If the entry is vacant and you want to call certain functions like or_insert, you need the actual key, not a reference to it, since you will at that point insert into the map. Note that we don’t know that the key supports Copy or Clone, so we can’t take a reference and clone it.

When you use get, however, you don’t need an actual value to insert. It’s just fine to take a reference, since you can compute Hash and Eq, which are required to determine if the key is in the map, using only a reference. This is more efficient if the key is large, and it can avoid a needless allocation.

In addition, get also allows you to use anything which implements Borrow for the key. Thus, if your key is a String, you can use a &str to get. This is great because your key might be owned, but you want to use a &str literal, like "foo", to look up in the map. In this case, no allocation is required at all because the string is hard-coded in the program’s code.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading