Given a library (for instance a GUI library) that uses callbacks to communicate events to the library user, how would I proceed to have proper mutability in the program? For instance:
// so I have this `obj` I want to modify when the user clicks buttons
// in the GUI
let same_action = move |_| {
// modify obj in several ways, e.g. obj.text = "Modified"
obj.text = "Modified";
}
// --> I had to move `obj` above since `on_click` has a `'static`
// constraint for `F` but that's not really a thing I want to do,
// I want to keep control of `obj` in the outer scope!!!
// --> error because `same_action` does not implement `Fn` since it
// mutates the moved `obj` in it
button1.on_click(same_action);
// --> if the above worked, here we'd have a error because `button1`
// has moved `same_action`
button2.on_click(same_action);
// --> assuming all of the above worked, we'd have a error here about
// unable to use `obj` because it has been moved to same_action
button3.on_click(move |_| obj.text = "Another modifier");
// the library now process the gui and call the callbacks in a loop
// until exit
gui_run();
// --> ..., error cannot use `obj` because it has been moved by
// `same_action`
println!("Final value: {}", obj.text);
See the comments with // -->
for the critical points of this question.
This seems like a pretty common problem to worry on event-driven APIs in Rust. How'd one get around it?