Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

HashMap should not take ownership of its keys #44271

Closed
Binero opened this issue Sep 2, 2017 · 2 comments
Closed

HashMap should not take ownership of its keys #44271

Binero opened this issue Sep 2, 2017 · 2 comments

Comments

@Binero
Copy link
Contributor

Binero commented Sep 2, 2017

Right now, to insert a new value into a std::collections::HashMap, one must transfer ownership of the key to the map. The map however does not seem to require ownership of the key.

The HashMap does not keep around a copy of the key however. It only stores its hash. This means that there is no way to get the key out of the HashMap again.

For example, take the signature of the insert method:

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

If the value is updated, it returns the old value, thus giving the user ownership of said value again. The key however, is lost forever. There is no way to get it back.

@Binero Binero changed the title HashMap should not take its keys by value HashMap should not take ownership of its keys Sep 2, 2017
@codyps
Copy link
Contributor

codyps commented Sep 2, 2017

HashMap does store the key, and references to that key can be retrieved by using HashMap::entry() and HashMap::keys() (among others).

One can use the HashMap::entry() api to retrieve the stored key on removal as well with remove_entry.

That said, getting an entry currently requires another owned key to pass to entry(). There is an rfc working on fixing that.

@Binero
Copy link
Contributor Author

Binero commented Sep 2, 2017

Aha, my bad. I got confused just now because surely it must store the key SOMEWHERE, otherwise the HashMap wouldn't be able to check within a bucket. The entry is exactly what I was looking for, thanks a ton!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants