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