首页 > 解决方案 > 如何避免'不能借用`*self`作为可变的,因为它也被借用为不可变的闭包?

问题描述

这是我的示例代码,以及下面的编译器错误。

struct A {
    value: i32,
    closure: Box<dyn Fn(&mut Self) -> ()>,
}

impl A {
    fn call_closure(&mut self) -> () {
        (self.closure)(self)
    }
}

fn main() {
    let _foo = A {
        value: 0,
        closure: Box::new(move |a: &mut A| {
            a.value = 10;
        }),
    };
}

error[E0502]: cannot borrow `*self` as mutable because it is also borrowed as immutable
 --> src/main.rs:8:9
  |
8 |         (self.closure)(self)
  |         --------------^^^^^^
  |         |
  |         mutable borrow occurs here
  |         immutable borrow occurs here
  |         immutable borrow later used by call

我理解为什么编译器会给出这个错误,但我希望这样的代码允许一个闭包作为字段来修改结构的字段。

有什么好的想法或设计吗?这里的惯用方式是什么?

标签: design-patternsrust

解决方案


推荐阅读