0

为什么以下代码在借用检查器中失败?

struct X(pub i32);
impl X {
    fn run<F>(&mut self, f: F) -> i32
    where
        F: FnOnce() -> i32,
    {
        f() * self.0
    }
}

struct Y {
    a: i32,
    b: X,
}
impl Y {
    fn testme(&mut self) -> i32 {
        let x = || self.a;
        self.b.run(x)
    }
}

fn main() {
    let mut x = Y { a: 100, b: X(100) };
    println!("Result: {}", x.testme());
}

出现错误(游乐场

error[E0502]: cannot borrow `self.b` as mutable because `self` is also borrowed as immutable
  --> src/main.rs:18:9
   |
17 |         let x = || self.a;
   |                 -- ---- previous borrow occurs due to use of `self` in closure
   |                 |
   |                 immutable borrow occurs here
18 |         self.b.run(x)
   |         ^^^^^^ mutable borrow occurs here
19 |     }
   |     - immutable borrow ends here

看起来像是x借来self的闭包testme();它不应该只是借来的self.a吗?也许我错过了一些东西。

4

0 回答 0