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

前端 未结 1 483
渐次进展
渐次进展 2020-12-06 12:20

I\'m trying to build a vector of points that are changed while iterating over them:

struct Point {
    x: i16,
    y: i16,
}

fn main() {
    let mut points:         


        
相关标签:
1条回答
  • 2020-12-06 13:11

    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.

    0 讨论(0)
提交回复
热议问题