首页 > 解决方案 > 在不同集合中存储对相同项目的引用:移动后借用的值

问题描述

假设我正在尝试创建一个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()
    ));
}

标签: rust

解决方案


推荐阅读