且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在迭代集合的同时修改集合?

更新时间:2022-06-18 23:59:23

有没有办法让这个代码就地"更新电路板?

Is there a way that I could make this code update the board "in place"?

存在一种专为此类情况而设计的类型.它巧合地称为 std::cell::Cell.你可以改变 Cell 的内容,即使它已经被多次不可变地借用了.Cell 仅限于实现 Copy 的类型(对于其他类型,您必须使用 RefCell,如果涉及多个线程,则必须使用 ArcMutex).

There exists a type specially made for situations such as these. It's coincidentally called std::cell::Cell. You're allowed to mutate the contents of a Cell even when it has been immutably borrowed multiple times. Cell is limited to types that implement Copy (for others you have to use RefCell, and if multiple threads are involved then you must use an Arc in combination with somethinng like a Mutex).

use std::cell::Cell;

fn main() {
    let board = vec![Cell::new(0), Cell::new(1), Cell::new(2)];

    for a in board.iter() {
        for b in board.iter() {
            a.set(a.get() + b.get());
        }
    }
    println!("{:?}", board);
}