Closed
Description
The following code does not compile:
use std::rc::Rc;
use std::cell::RefCell;
pub struct Callbacks {
callbacks: Vec<Rc<RefCell<FnMut(i32)>>>,
}
impl Callbacks {
pub fn call(&mut self, val: i32) {
for callback in self.callbacks.iter() {
let mut closure = callback.borrow_mut();
closure(val);
}
}
}
(Playpen)
It says: "cannot borrow immutable borrowed content as mutable".
Instead, I have to explicitly dereference and borrow the closure in the loop, with (&mut *closure)(val)
. Typically, Rust performs this automatically, so I expected that to also happen in this case. At the very least, the error message should be improved, as currently, it doesn't help with the actual issue at all.