我正在尝试构建一个在迭代它们时发生变化的点的向量:
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: 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正如我在这里所学,Rust 不允许在迭代时修改结构,从而导致错误.
As I learned here, Rust doesn't allow modifying the structure while iterating over it, thus the error.
如何以优雅的方式修改它?如果我阅读这个答案并得到它然后我想到了以下内容:
How do I modify it in an elegant way? If I read this answer and get it right then the following comes to my mind:
虽然我认为我可以让 (1) 工作,但我对所有这些流行和推动并不满意(无论如何,这是高性能的吗?).关于 (2),我不知道如何让它工作 - 如果这会奏效.
While I think I can get (1) working, I'm not really happy about all this pop's and push's (is this high-performance anyhow?). Concerning (2), I have no idea how to get it working - if this would work at all.
问题:
您不能修改正在迭代的结构,即向量points.但是,修改您从迭代器获得的元素完全没有问题,您只需要选择可变性:
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 {可变性是可选的,因为可变迭代进一步限制了您在迭代时可以对 points 执行的操作.由于可变别名(即两个或多个指向同一内存的指针,其中至少一个是 &mut)被禁止,因此您甚至无法从 读取>points 而 iter_mut() 迭代器在附近.
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.
更多推荐
在迭代时修改结构是否有优雅的解决方案?
发布评论