design-patterns - 如何避免'不能借用`*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
我理解为什么编译器会给出这个错误,但我希望这样的代码允许一个闭包作为字段来修改结构的字段。
有什么好的想法或设计吗?这里的惯用方式是什么?
解决方案
推荐阅读
- c - 如何处理纯 C 中的严格枚举?
- c# - 为什么我枯燥的 Newtonsoft.Json 反序列化代码不起作用?
- r - 如何根据 R 中的独特组找到均值/中值/众数?
- spring - Mybatis sql mapper xml中是否可以将CLOB数据转换为String?
- javafx - JavaFX FXMLLoader 找不到 .fxml 文件的路径
- c# - 有人可以帮我统一展示正确的场景级别吗?
- c# - 使用 Refit 包含空查询参数
- r - 如何使用 rvest 包提取 html 的折叠信息?
- sql - wordpress数据库的where子句中的未知列
- android - 我怎样才能等到 onsuccess 侦听器在 Kotlin 中得到结果