Here is my struct and I need a get_mut
function that returns a mutable reference to a value owned either by
ctx.scope
or ctx.parent.scope
recursively
pub type RuntimeContext<'c> = Rc<RefCell<Context<'c>>>;
pub struct Context<'c> {
pub parent: Option<RuntimeContext<'c>>,
pub scope: HashMap<String, Value>,
pub eval: Value,
}
This is what I tried, but as expected the borrow checker complains:
error[E0515]: cannot return reference to temporary value
--> src/lib.rs:20:13
|
20 | parent.borrow_mut().get_mut(key) // here it breaks
| -------------------^^^^^^^^^^^^^
| |
| returns a reference to data owned by the current function
| temporary value created here
What other way is there to achieve this?
(the parent ctx is guaranteed to outline the current ctx)
impl<'c> Context<'c> {
pub fn get_mut(&mut self, key: &str) -> Option<&mut Value> {
if let Some(v) = self.scope.get_mut(key) {
Some(v)
} else if let Some(parent) = &mut self.parent {
parent.borrow_mut().get_mut(key) // here it breaks
} else {
None
}
}
// ... some other methods
}