rust / expert
Snippet
Enforcing Lifetime Invariance via PhantomData
By default, references and types parameterizing lifetimes are covariant. However, types that allow mutation (like mutable references or cells) must be invariant over their type parameters and lifetimes to prevent unsound reference sharing. Using PhantomData<fn(&'a T) -> &'a T> forces lifetime invariance for the generic lifetime 'a.
snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
use std::marker::PhantomData;struct CellRef<'a, T> {value: *mut T,_marker: PhantomData<fn(&'a T) -> &'a T>,}impl<'a, T> CellRef<'a, T> {fn new(val: &'a mut T) -> Self {CellRef { value: val as *mut T, _marker: PhantomData }}}
Breakdown
1
_marker: PhantomData<fn(&'a T) -> &'a T>
Uses a function signature in PhantomData to make the lifetime 'a invariant, as the parameter appears in both covariant and contravariant positions.
2
value: *mut T
A raw mutable pointer which lacks lifetime constraints, necessitating the manual application of PhantomData to bind the lifetime.