在借用可变 self 的函数的参数中修复 self 的可变借用的方法

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

我有一些这样的代码 (playground)。为什么编译器认为这是一个问题?我怎样才能解决这个问题而不添加新的变量来存储编译器告诉的参数?

代码:

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[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());
   |     ^^^^^^^^^^^^^^

除此之外,您的方法不需要 &mut,这只是为了示例。

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

目前,您不能。方法是移动内部结果,所以借用在下次调用时解锁:

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

Playground