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

Iterator over entries of Hash* #33549

Closed
nagisa opened this Issue May 10, 2016 · 4 comments

Comments

Projects
None yet
6 participants
@nagisa
Copy link
Contributor

nagisa commented May 10, 2016

An iterator over entries of HashMap/Set could be added?

@eefriedman

This comment has been minimized.

Copy link
Contributor

eefriedman commented May 10, 2016

HashMap already has a method iter_mut(); could you describe what you want a bit more precisely?

@nagisa

This comment has been minimized.

Copy link
Contributor Author

nagisa commented May 10, 2016

@eefriedman Consider following code which could potentially be a poor-man’s implementation of pop:

for entry in map.entries() {
    if let Entry::Occupied(o) = entry {
        return o.remove();
    } else { unreachable!() }
}

That cannot be implemented with iter_mut() today.

@apasel422

This comment has been minimized.

Copy link
Member

apasel422 commented May 11, 2016

I'm not sure that the current HashMap design would support the existence of multiple OccupiedEntrys at the same time (due to the relocation of entries during removal), but if such an iterator were added, I expect that its item type would be OccupiedEntry rather than Entry, as a VacantEntry cannot be created without a key.

@dtolnay

This comment has been minimized.

Copy link
Member

dtolnay commented Nov 15, 2017

I agree with @apasel422 that I don't think this will work with an iterator of entries. The Iterator trait permits the caller to hold on to multiple items at the same time, which in this case would mean multiple items that each have mutable access to the same HashMap.

I think the use case of iterating over key-value pairs and conditionally removing them efficiently is addressed by HashMap::retain which was added in #36648, after this issue was opened, so I think this can be considered done.

@dtolnay dtolnay closed this Nov 15, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.