2

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 the compiler 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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
atsisy
  • 21
  • 1
  • *that allows a closure [...] to modify fields of the structure* — and what happens if the closure attempts to modify the closure itself (`a.closure = ...`)? – Shepmaster Nov 11 '19 at 16:18
  • Therefore, in order to prevent that closure attempts to modify the closure itself, such code is prohibited in Rust? – atsisy Nov 11 '19 at 16:40
  • That's correct. The primary refactoring is to [split up your code into multiple parts](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=267b2972bae7f784152a90d40a30f435). – Shepmaster Nov 11 '19 at 16:48
  • OK! Thank you very much for fast answer! I'm sorry for my bad English. I will rethink about my program design. – atsisy Nov 11 '19 at 16:55
  • No need to apologize for your English — you communicated your point just fine! I just tidy up almost every question / answer to help make [tag:rust] as good as possible. – Shepmaster Nov 11 '19 at 16:56

0 Answers0