如何在迭代期间改变向量的项目?

How to mutate items of a vector during iteration?

我有一个 Vec 结构。当使用 .iter() 遍历此 Vec 时,我想编辑 for 循环内的每个元素,但我收到一条错误消息,指出每个元素都已被借用,我该如何解决这个问题?这是一个小代码示例:

struct complex_struct {
    attr1: i32
}
    
let elements: Vec<complex_struct> = generate_data();
    
for element in elements.iter() {
    element.attr1 = 0;
}

使用 iter_mut 从迭代器中获取可变元素:

#[derive(Debug)]
struct ComplexStruct {
    attr1: i32
}

fn main() {
    let mut elements: Vec<ComplexStruct> = vec![ComplexStruct { attr1: 5 }];

    for element in elements.iter_mut() {
        element.attr1 = 0;
    }
    
    dbg!(elements); // prints out [ComplexStruct { attr1: 0 }]
}

playground