1

Let's say I'm trying to create a GameBoard where I have a list/vec of Pieces and references to those pieces on a 2-dimensional grid like this:

#[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],
}

How can I move a Piece to the list but also its reference to the grid? I get borrow after move error. Is this possible to do in 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
}

EDIT + Answer?

This seems to work:

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()
    ));
}
lxe
  • 7,051
  • 2
  • 20
  • 32
  • Kind of. I think it's the same issue but I'm getting a slightly different error. In any case I'll close/mark as duplicate. – lxe Nov 29 '20 at 20:43
  • 1
    Even though your answer compiles, it isn't really a solution. It only appears to work because you don't modify `list` again. Adding the reference to the grid will stop you from mutating it again. You also won't be able to move `board` because of the self-referential lifetime constraints. See: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=a8b234b39ad7ab28575d29191bf55ef3 – kmdreko Nov 30 '20 at 20:41

0 Answers0