error[E0499]: cannot borrow `*self` as mutable more than once at a time?

How can I call get_chessboard in the code below?

error[E0499]: cannot borrow `*self` as mutable more than once at a time
  --> src/main.rs:81:36
   |
81 |         self.player.set_chessboard(self.get_chessboard());
   |         ----------- -------------- ^^^^ second mutable borrow occurs here
   |         |           |
   |         |           first borrow later used by call
   |         first mutable borrow occurs here


impl Game {
    fn new() -> Game { ... }
    fn get_chessboard(&mut self) -> RenderBuffer { ... }

    fn on_load(&mut self, w: &mut PistonWindow) {
        self.player.set_chessboard(self.get_chessboard()); // HERE
                                                      ^
    }
}

A temporary variable seems to be the simplest solution.

let chessboard = self.get_chessboard();
self.player.set_chessboard(chessboard);
drop(chessboard); // if necessary

This is because the order of execution is left to right, like this:

let tmp1 = &mut self.player;
let tmp2 = self.get_chessboard();
tmp1.set_chessboard(tmp2);

so by the time Rust starts evaluating arguments to the method call, it has already locked self.player for exclusive access, so nothing else can touch self.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.