在迭代时修改结构是否有优雅的解决方案? [英] Is there an elegant solution to modifying a structure while iterating?

查看:40
本文介绍了在迭代时修改结构是否有优雅的解决方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试构建一个在迭代它们时发生变化的点的向量:

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. 创建一个临时结构,我将更改的项目推送到其中并用循环外的临时结构替换原始结构(如何?).

虽然我认为我可以让 (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.

问题:

  1. (2) 是一个解决方案吗?如果是,它会是什么样子?
  2. 还有其他解决方案吗?
  3. 不同解决方案的优缺点是什么,尤其是在性能方面?

推荐答案

您不能修改正在迭代的结构,即向量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)被禁止,因此您甚至无法从 读取>pointsiter_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.

这篇关于在迭代时修改结构是否有优雅的解决方案?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆