This question already has an answer here:
Here is my sample code, and the compiler error beneath.
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
I understand why rustc gives this error, but I'm hoping for code like this that allows a closure as field to modify fields of the structure.
Are there any good ideas or designs? What is the idiomatic way here?
Aucun commentaire:
Enregistrer un commentaire