Mutating the same data in multiple 'static closures

前端 未结 1 379
走了就别回头了
走了就别回头了 2021-01-20 05:45

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

相关标签:
1条回答
  • 2021-01-20 06:17

    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<TheObject>/Cell<TheObject>, or
    • TheObject where some fields are Cells and RefCells.

    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.

    0 讨论(0)
提交回复
热议问题