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())
}
5 Likes
Thanks so much.