I need to put closures behind <Rc<RefCell<T>>
for some reason:
- multiple references to closure;
- closure can modify environment(interior mutability);
- 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?