How can I modify a collection while also iterating over it?

前端 未结 2 1170
抹茶落季
抹茶落季 2020-12-06 12:50

I have a Board (a.k.a. &mut Vec>) which I would like to update while iterating over it. The new value I want to update wi

2条回答
  •  失恋的感觉
    2020-12-06 13:25

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

    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);
    }
    

提交回复
热议问题