We know that it's easy to convert a value of type RefCell<T> to a value of type &T for use as a parameter in a function:
fn main() {
let a: RefCell<i32> = RefCell::new(0);
my_func(a.borrow().deref());
}
fn my_func(i: &i32) {}
In my scenario, the RefCells are stored in a HashMap, so they get obtained wrapped in an Option. I also want the function I pass them to have the notion of option, but I only want to pass the non-mutable reference, not the whole RefCell. We can achieve this like so:
fn main() {
let a: Option<RefCell<i32>> = Some(RefCell::new(0));
match a {
Some(ref_cell) => my_func(Some(ref_cell.borrow().deref())),
None => my_func(None)
};
}
fn my_func(i: Option<&i32>) {}
This works, but in my specific scenario, my_func takes several of these Option<&T>s as a parameter, so doing it this way means the match just gets nested for each parameter and grows exponentially. It would therefore be helpful to have someway of doing this:
fn main() {
let a: Option<RefCell<i32>> = Some(RefCell::new(0));
let c = match a {
Some(ref_cell) => Some(ref_cell.borrow().deref()), // won't compile as this borrow won't live long enough
None => None
};
my_func(c);
}
fn my_func(i: Option<&i32>) {}
So essentially I want to be able to convert from Option<RefCell<T>> to Option<&T>. I feel like this should be possible somehow but I can't figure out a way to do it. I always run into some issue of performing the .borrow() on the RefCell but it not living long enough.