rust - 在不同集合中存储对相同项目的引用:移动后借用的值
问题描述
假设我正在尝试创建一个GameBoard
我有一个列表/vecPieces
并引用二维网格上的这些片段的位置,如下所示:
#[derive(Default, Debug)]
struct Piece;
#[derive(Default, Debug)]
struct Board<'a> {
// List of piece instances
list: Vec<Piece>,
// References to pieces in the above list but on a grid
grid: [[Option<&'a Piece>; 8]; 8],
}
我怎样才能将 a 移动Piece
到 the ,list
但它对 的引用也可以grid
?移动错误后我借了。这可以在 Rust 中做到吗?
fn main() {
let mut board: Board = Default::default();
let piece = Piece;
// Move piece to the board.list
board.list.push(piece);
// Error: borrow of moved value: `piece`
// value borrowed here after moverustc(E0382)
board.grid[0][0] = Some(&piece); // Borrow after move error
}
编辑+回答?
这似乎有效:
fn main() {
let mut board: Board = Default::default();
let piece = Piece;
// Move piece to the board.list
board.list.push(piece);
// This returns an Option<&Piece> so we can then place it in grid
board.grid[0][0] = board.list.last();
// Looks good!
assert!(ptr::eq(
board.list.last().unwrap(),
board.grid[0][0].unwrap()
));
}
解决方案
推荐阅读
- ios - 如何快速使用和访问 App Bar Bottom(Material Design)?
- javascript - Firestore FieldValue.increment()
- java - 为什么我不能“直接”从 HTML 调用 Servlet?
- javascript - 当动态添加的 div 被删除时,最后创建的 div 会跟随它
- python - 'RegisterAPI' 应该包含一个 `serializer_class` 属性,或者覆盖 `get_serializer_class()` 方法
- javascript - 你可以设置自动完成的文本吗?
- javascript - 在java脚本中休息/传播
- python - Python中的列表计数器
- parsing - 使用包含“:”冒号的关系名称创建 Semgrex 模式时出现问题
- design-patterns - 观察者模式和依赖倒置