I need a vector of closures which I declared but I cannot use items of the vector due to compile error.
cannot borrow
**has mutable, as it is behind a&reference
is it possible to get the code working without dynamic memory allocation? and why h being borrowed as mutable?
fn main() {
let hh: Vec<&dyn FnMut(&mut i32)> = vec![&|i: &mut i32| {
*i = 10;
}];
let mut i = 0;
let h = &hh[0];
h(&mut i); // <-- cannot borrow `**h` as mutable, as it is behind a `&` reference
println!("{}", i);
}
I have made above example works but in this case I need to declare variables for each item which looks overabundant
fn main() {
let mut item = |i: &mut i32| {
*i = 10;
};
let mut hh: Vec<&mut dyn FnMut(&mut i32)> = vec![&mut item];
let mut i = 0;
let h = &mut hh[0];
h(&mut i);
println!("{}", i);
}
is there an elegant solution?