我试图构建一个点向量,这些点在迭代过程中发生了变化:
struct Point {
x: i16,
y: i16,
}
fn main() {
let mut points: Vec<Point> = vec![];
// unsure if point is mutable
points.push(Point { x: 10, y: 10 });
// thus trying it explicitly
let mut p1 = Point { x: 20, y: 20 };
points.push(p1);
for i in points.iter() {
println!("{}", i.x);
i.x = i.x + 10;
}
}
编译时,我得到一个错误:
error[E0594]: cannot assign to immutable field `i.x`
--> src/main.rs:16:9
|
16 | i.x = i.x + 10;
| ^^^^^^^^^^^^^^ cannot mutably borrow immutable field
正如我在here中了解到的,Rust不允许在迭代时修改 struct ,因此会出现错误.
如何以优雅的方式修改它?如果我读了this answer并把它读对了,我就会想到以下几点:
- 从矢量中弹出项目,修改它并将其推回.
- 如何创建临时 struct (如何将临时 struct 替换为临时 struct ?).
虽然我认为我可以开始工作,但我对这些流行音乐和推送音乐并不满意(这是高性能的吗?).关于(2),我不知道如何让它工作——如果这真的能工作的话.
Questions:
- (2)是一种解决方案吗?如果是,它会是什么样子?
- 还有其他解决方案吗?
- 不同解决方案的优缺点是什么,尤其是在性能方面?