I am trying to extract two elements from Vec that will always contain at least two elements. These two elements need to be retrieved with the change, since I need to be able to change the values as part of a single operation.
Code example:
struct Piece { x: u32, y: u32, name: &'static str } impl Piece { fn exec(&self, target: &mut Piece) { println!("{} -> {}", self.name, target.name) } } struct Board { pieces: Vec<Piece> } fn main() { let mut board = Board { pieces: vec![ Piece{ x: 0, y: 0, name: "A" }, Piece{ x: 1, y: 1, name: "B" } ] }; let mut a = board.pieces.get_mut(0); let mut b = board.pieces.get_mut(1); a.exec(b); }
Currently, this fails with the following compiler errors:
piece.rs:26:17: 26:29 error: cannot borrow `board.pieces` as mutable more than once at a time piece.rs:26 let mut b = board.pieces.get_mut(1); ^~~~~~~~~~~~ piece.rs:25:17: 25:29 note: previous borrow of `board.pieces` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `board.pieces` until the borrow ends piece.rs:25 let mut a = board.pieces.get_mut(0); ^~~~~~~~~~~~ piece.rs:28:2: 28:2 note: previous borrow ends here piece.rs:17 fn main() { ... piece.rs:28 }
Unfortunately, I should be able to get a mutable link to both so that I can change both inside the Piece.exec method. Any ideas, or am I trying to do it wrong?
source share