How to get a ref to T in RefCell<Option<T>>

use std::cell::RefCell;

#[derive(Debug)]
struct Foo<T> {
    data: RefCell<Option<T>>,
}

impl<T> Foo<T>
where
    T: Default,
{
    fn new() -> Self {
        Self {
            data: RefCell::new(Some(T::default())),
        }
    }
    

    fn get_inside_ref<'a>(&'a self) -> &'a T {
        todo!()
    }
}

I tried a lot of ways,but still can't get rid of dangling references

That's impossible for the same reason you can't have a mapping from RefCell<T> to &T - you must have Ref<'_, T> alive to get a borrow of T inside a RefCell, otherwise it'd be unchecked access to protected data[1].

It's possible to return Ref<'a, T>, though, like this:

fn get_inside_ref<'a>(&'a self) -> Ref<'a, T> {
    Ref::map(self.data.borrow(), |optref| optref.as_ref().unwrap())
}

  1. Well, strictly speaking, there's Ref::leak, but it, as the name suggests, leaks the Ref and holds RefCell immutable borrowed forever. ↩ī¸Ž

5 Likes

Thanks so much.