<分区>
这是有趣的部分:
struct S1 {}
impl S1 {
pub fn new() -> Self {
S1 {}
}
pub fn foo<F>(&self, mut delegate: F) -> ()
where
F: FnMut() -> (),
{
delegate()
}
}
struct S2 {
s1: S1,
done: bool,
}
impl S2 {
pub fn new() -> Self {
S2 {
s1: S1::new(),
done: false,
}
}
fn actually_do_something(&mut self) -> () {
self.done = true
}
pub fn do_something(&mut self) -> () {
self.s1.foo(|| {
self.actually_do_something();
})
}
}
实际产生的错误是:
error[E0500]: closure requires unique access to `self` but `self.s1` is already borrowed
--> src/main.rs:34:21
|
34 | self.s1.foo(|| {
| ------- ^^ closure construction occurs here
| |
| borrow occurs here
35 | self.actually_do_something();
| ---- borrow occurs due to use of `self` in closure
36 | })
| - borrow ends here
我明白为什么会出现此错误(self
有多个重叠的可变借用),但我找不到合适的方法来解决它。在这里对我的对象进行多次深度引用似乎是不可能的,因为我直接调用了 self
方法。