为什么以下代码在借用检查程序中失败?
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());
}
错误(Playground)
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
吗?也许我错过了什么。