Skip to content

Detect and fail when hashmap is modified during iteration #2050

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

Closed
nikomatsakis opened this issue Mar 23, 2012 · 4 comments
Closed

Detect and fail when hashmap is modified during iteration #2050

nikomatsakis opened this issue Mar 23, 2012 · 4 comments
Assignees

Comments

@nikomatsakis
Copy link
Contributor

Related to #2049, I think we ought to detect attempts to modify hashmaps and other mutable data structures during iteration and fail fast. This should be relatively easy to do thanks to the use of methods to define when iteration is occurring. We can also allow certain kinds of modifications (for example, only the current key) if desired.

@marijnh
Copy link
Contributor

marijnh commented Mar 23, 2012

I think this is too restrictive. Updating or removing the item currently being pointed at is extremely useful, and not hard to support. Forcing people to write their own update list when doing a modifying pass over a map would be an admission of defeat wrt usability.

@nikomatsakis
Copy link
Contributor Author

We could allow modification to the current key, but I would be inclined to add a mapValues method instead. It is more efficient (no need to rehash) and more declarative of the intention.

@ghost ghost assigned nikomatsakis Apr 6, 2012
@thestinger
Copy link
Contributor

I think this can probably be closed now. Iterating over an owned data structure requires it to be frozen first, and it only ever makes sense to modify a value (not a key) since touching a key would ruin the data structure invariants. Both treemap and hashmap are owned maps and oldmap is deprecated, and all future mutable data structures should be owned.

A method for iterating over the container and modifying the values in-place would definitely be a good idea.

@thestinger
Copy link
Contributor

A mutate_values method is added in #5365, and I think that covers 99% of the functionality that would be possible by mutating while iterating. It's possible to allow removing entries while iterating... but it would require unsafe blocks to actually implement it for most of the containers.

Closing this anyway because there's no way to actually mutate it while using normal iteration or lazy iterators since they both freeze it.

celinval pushed a commit to celinval/rust-dev that referenced this issue Jun 4, 2024
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

3 participants