Rust 闭包指的是一种自我:借用错误的方法
以下是有趣的部分:Rust 闭包指的是一种自我:借用错误的方法,rust,Rust,以下是有趣的部分: 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, don
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();
})
}
}
我理解为什么会出现这个错误(有多个重叠的self
可变借词),但我找不到合适的方法来解决它。在这里对我的对象进行多个深度引用似乎是不可能的,因为我正在直接调用self
方法。一种方法是。以下是您的代码示例:
pub fn do_something(&mut self) -> () {
let &mut S2 { ref mut s1, ref mut done } = self;
s1.foo(|| {
*done = true;
})
}