I have a RefCell
in my structure which I want to access and modify. However, the only way I can access this RefCell
is using a closure. Hence, I'd like to return a mutable reference (RefMut
) from the closure which I can use and modify from the enclosing scope.
{
let mut state_ref: RefMut<_> = self.dialog.call_on_name("dirview", |view: &mut Canvas<RefCell<FileDialogState>>| {
let state: &RefCell<FileDialogState> = view.state_mut();
state.borrow_mut()
}).unwrap();
state_ref.foo = bar;
// Mutable reference to RefCell should cease to exist here
}
However, the compiler complains that the RefMut
I am returning outlives the lifetime of the closure where I create it.
Despite this, I've seen code which does something similar to what I'm trying to achieve -- for example here:
impl Backend {
pub fn init() -> ... {
let stdout = RefCell::new(BufWriter::new(io::stdout()));
...
}
fn stdout_mut(&self) -> RefMut<BufWriter<Stdout>> {
self.stdout.borrow_mut()
}
What is the difference between these two use cases? What am I missing to be able to return the RefMut
reference?