关闭是指一种自我的方法:借用错误

时间:2017-02-24 09:37:32

标签: 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,
    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方法。

1 个答案:

答案 0 :(得分:1)

这样做的方法是destructure your struct。以下是您的代码示例:

pub fn do_something(&mut self) -> () {
    let &mut S2 { ref mut s1, ref mut done } = self;
    s1.foo(|| {
        *done = true;
    })
}

Playground