在迭代时修改结构是否有优雅的解决方案?

编程入门 行业动态 更新时间:2024-10-10 12:24:59
本文介绍了在迭代时修改结构是否有优雅的解决方案?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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.

    问题:

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

    您不能修改正在迭代的结构,即向量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.

    更多推荐

    在迭代时修改结构是否有优雅的解决方案?

    本文发布于:2023-11-29 01:47:17,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1644804.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:优雅   解决方案   结构   迭代

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!