0

I need to put closures behind <Rc<RefCell<T>> for some reason:

  1. multiple references to closure;
  2. closure can modify environment(interior mutability);
  3. closure is better stored as trait object because eventually I want to put references inside a vector.

However, closures become unusable when stored as trait object.

Here is an example. To simply, variable closure doesn't mutate environment. In my own use case, I do need mutate environment.

type Handler = FnMut(&mut u32);

let closure: rc::Rc<cell::RefCell<Handler>> = rc::Rc::new(cell::RefCell::new(|x: &mut u32|{
// would work if above line is:
// let closure: = rc::Rc::new(cell::RefCell::new(|x: &mut u32|{
    *x = 3;
}));

let mut y = 0u32;

let cc = closure.borrow_mut();

cc(&mut y);

I know that it would work if I remove the type contraint on variable closure. But that way I lost the ability to put similar closures inside vec.

Is there a way to use closure behind <Rc<RefCell<T>>? Or is there other alternative in rust to meet the 3 requirements I listed?

Xiwen Li
  • 1,155
  • 8
  • 15
  • 1
    You don't *need* `FnMut` here (and hence don't need to borrow mutably or even use `RefCell` at all), since there are no variables moved into the closure so it doesn't have its own state. You only have a mutable parameter, but the closure itself doesn't mutate. – Frxstrem May 24 '19 at 16:59
  • 2
    To apply the answer in the duplicate I linked, you just need to change the second to last line to `let cc = &mut *closure.borrow_mut();` – Wesley Wiser May 24 '19 at 17:01
  • 2
    You are right. That solves my problem. Thank you Wesley. – Xiwen Li May 24 '19 at 17:19

0 Answers0