YMO4
YMO4

Reputation: 58

Ways to fix muttable borrowing of self in arguments to function that borrows muttable self

I have some code like this (playground). Why does the compiler think it's a problem? How can i solve this problem without adding new variable that storing argument as the compiler tells?

Code:

struct A {}

impl A {
    fn foo(&mut self, i: i32) -> i32 {
        i
    }
    
    fn bar(&mut self) -> i32 {
        1
    }
}

fn main() {
    let mut b = A{};
    b.foo(b.bar());
}

Error:

error[E0499]: cannot borrow `b` as mutable more than once at a time
  --> src/main.rs:15:11
   |
15 |     b.foo(b.bar());
   |     ------^^^^^^^-
   |     | |   |
   |     | |   second mutable borrow occurs here
   |     | first borrow later used by call
   |     first mutable borrow occurs here
   |
help: try adding a local storing this argument...
  --> src/main.rs:15:11
   |
15 |     b.foo(b.bar());
   |           ^^^^^^^
help: ...and then using that local as the argument to this call
  --> src/main.rs:15:5
   |
15 |     b.foo(b.bar());
   |     ^^^^^^^^^^^^^^

Upvotes: 0

Views: 368

Answers (1)

Netwave
Netwave

Reputation: 42678

Taking apart that your methods do not need to be &mut and that is just for the example.

How can i solve this problem without adding new variable that storing argument as the compiler tells?

At the moment, you can't. The way is to move the inner result, so the borrow is unlocked on the next call:

fn main() {
    let mut b = A{};
    let i = b.bar();
    b.foo(i);
}

Playground

Upvotes: 2

Related Questions