为什么看起来像一个封闭借用自我而不是自我领域?

时间:2018-06-04 02:44:30

标签: rust self borrow-checker borrowing

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

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

看起来封闭xself中借用了testme();它不应该只借用self.a吗?也许我错过了什么。

0 个答案:

没有答案
相关问题