Is there an elegant solution to modifying a structure while iterating?

You cannot modify the structure you are iterating over, that is, the vector points. However, modifying the elements that you get from the iterator is completely unproblematic, you just have to opt into mutability:

for i in points.iter_mut() {

Or, with more modern syntax:

for i in &mut points {

Mutability is opt-in because iterating mutably further restricts what you can do with points while iterating. Since mutable aliasing (i.e. two or more pointers to the same memory, at least one of which is &mut) is prohibited, you can’t even read from points while the iter_mut() iterator is around.

Leave a Comment