rust - 引用 self : borrow error 方法的闭包

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

最佳答案

这样做的一种方法是 destructure your struct .这是您的代码示例:

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

Playground

关于rust - 引用 self : borrow error 方法的闭包,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42435216/

相关文章:

rust - 如何从特征对象中获取对具体类型的引用?

for-loop - Rust 中的 for 循环变体之间有什么区别?

macos - 通过带有 Rust FFI 的 GLUT 打开的窗口卡住

rust - 我如何从方法中改变结构的字段?

struct - 递归打印 struct in `fmt::Display`

rust - 为什么在 Rust 中处理自定义错误类型时会出现运行错误?

objective-c - Rust Cocoa - 如何迭代 NSArray

rust - 将数据附加到 Actix-web 中的代理响应

io - 如何在超时的情况下从终端读取 UTF-8 字符?

rust - 获取TakeWhile的长度?