Hey I've recently found myself in a situation where I basically want a &'a T as the type of a struct field, but don't want to deal with passing in a reference when constructing the struct, basically owning the data but only ever getting immutable references to it.
So I've decided to try to implement the following to help with that:
struct ImmutableCell<'a, T>
where
T: 'a,
{
data: UnsafeCell<T>,
_p: PhantomData<&'a T>,
}
impl<'a, T> ImmutableCell<'a, T>
where
T: 'a,
{
fn new(data: T) -> Self {
Self {
data: UnsafeCell::new(data),
_p: PhantomData,
}
}
fn get(&self) -> &'a T {
unsafe { &*self.data.get() }
}
}
In my mind this should be fully sound since there is no way to modify the data once passed into a ImmutableCell, but i am not sure about that. Would love some comments