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
If you need to share mutable data, you need some container that make sure that the aliasing rules are being followed, most likely one from std::cell. For Copy
data this is Cell
, for other types there's RefCell
. Then the closures can use either:
Cell
/Cell
, orTheObject
where some fields are Cell
s and RefCell
s.Which is better depends on how granular you want the mutability to be and whether this is a common need for all users of TheObject
or just for this particular closure. In the second case, you need to alter the definition of TheObject
, in the first you'd do something like this:
let obj = RefCell::new(obj);
let same_action = move |_| {
obj.borrow_mut().text = "Modified";
}
If you furthermore can't have borrows in the closure's captured values, for example because of a 'static
bound, you can put the RefCell
into an Rc
.
Also, you can't pass same_action
to two buttons because closures can't be copied or cloned. In general this can't be done, because they might close over things that can't be copied or cloned. When possible, it may be allowed in the future, for now you can work around it with a macro, a function (that would have to box the closure), or by simply writing the closure twice if it's simple.