I have a function that tries to return a Ref out of a Refcell. The reference is behind an Option, and I'd like to be able to return the reference or an error if the Option is None.
Currently, I am checking beforehand if there it is none and returning an error if it is. Afterwards, I am calling unwrap() on the Option inside Ref::map in order to return the object.
Is there a more ergonomic way to do this? This seems very annoying to do (multiple borrows(), etc.) Option has a method ok_or that turns it into a Result type. Is there a way to use that here?
Here is a Rust playground to reproduce the minimal example:
pub fn get_thing_convenience(&self) -> Result<Ref<f32>, Box<dyn Error>> {
if self.thing.borrow().is_none() {
return Err(Box::new(MyError("blah".into())))
}
let thing = Ref::map(self.thing.borrow(), |t| t.unwrap());
Ok(thing)
}