【发布时间】:2015-09-07 03:10:30
【问题描述】:
我有一个Board(又名&mut Vec<Vec<Cell>>),我想在迭代它时对其进行更新。我要更新的新值来自一个函数,该函数需要 &Vec<Vec<Cell>> 到我正在更新的集合。
我已经尝试了几件事:
使用
board.iter_mut().enumerate()和row.iter_mut().enumerate()以便我可以更新最内层循环中的cell。 Rust 不允许调用next_gen函数,因为它需要&Vec<Vec<Cell>>并且当你已经有一个可变引用时你不能有一个不可变引用。将
next_gen函数签名更改为接受&mut Vec<Vec<Cell>>。 Rust 不允许对一个对象进行多个可变引用。
我目前将所有更新推迟到 HashMap,然后在我执行完迭代后应用它们:
fn step(board: &mut Board) {
let mut cells_to_update: HashMap<(usize, usize), Cell> = HashMap::new();
for (row_index, row) in board.iter().enumerate() {
for (column_index, cell) in row.iter().enumerate() {
let cell_next = next_gen((row_index, column_index), &board);
if *cell != cell_next {
cells_to_update.insert((row_index, column_index), cell_next);
}
}
}
println!("To Update: {:?}", cells_to_update);
for ((row_index, column_index), cell) in cells_to_update {
board[row_index][column_index] = cell;
}
}
有没有办法让这段代码“就地”更新board,即在最内层循环内,同时仍然能够在最内层循环内调用next_gen?
免责声明:
我正在学习 Rust,我知道这不是最好的方法。我在玩,看看我能做什么,不能做什么。我也试图限制任何复制以限制自己一点。作为oli_obk - ker mentions, this implementation for Conway's Game of Life is flawed。
这段代码旨在衡量几件事:
- 如果这是可能的
- 如果是惯用的 Rust
根据我在 cmets 中收集到的信息,std::cell::Cell 是可能的。但是,使用 std:cell:Cell 会绕过一些核心 Rust 原则,我在原始问题中将其描述为我的“困境”。
【问题讨论】:
标签: collections iterator rust immutability