Sub topic 8
PhantomData: choosing the variance you want
This chapter assumes you know what covariant, contravariant and invariant mean for a lifetime (the previous chapters cover them). It also assumes you can read generics and for<'a> bounds. Here you will learn how to use PhantomData to set the variance of your own types.
The problem: a parameter the fields do not use
Rust requires every lifetime and type parameter on a struct to appear in a field. If it does not, the compiler rejects the struct with error E0392 ("parameter is never used").
// Does not compile: error[E0392]: lifetime parameter `'a` is never used
// struct Handle<'a> {
// id: u32,
// }Sometimes the parameter is meaningful even though no field stores it. A handle might be valid only while some arena is borrowed. A struct might own a T through a raw pointer. A token might need to be tied to one particular scope. PhantomData<T> is a zero-sized type that makes the parameter "used" without storing any data.
use std::marker::PhantomData;
struct Handle<'a> {
id: u32,
_borrow: PhantomData<&'a ()>,
}
fn main() {
let h = Handle { id: 7, _borrow: PhantomData };
println!("{}", h.id);
}PhantomData<&'a ()> takes no space. It still tells the compiler that Handle<'a> behaves as if it held a &'a ().
The rule: PhantomData<T> has the variance of T
PhantomData<T> is covariant in T. For variance, the compiler treats PhantomData<X> as a field of type X. So the type you put inside PhantomData decides the variance of your struct. The result is the combination of all fields: a parameter is covariant only if every use is covariant, and any use that forces invariance makes the whole struct invariant.
| Marker type | Variance in `'a` / `T` | Typical use |
|---|---|---|
| `PhantomData<&'a T>` | covariant in `'a` and `T` | "I borrow a `T` for `'a`" |
| `PhantomData<&'a mut T>` | covariant in `'a`, invariant in `T` | "I hold an exclusive borrow" |
| `PhantomData<T>` | covariant in `T` | "I own a `T`" (also affects drop check) |
| `PhantomData<Cell<&'a ()>>` | invariant in `'a` | Branding a lifetime so it cannot be shrunk |
| `PhantomData<fn(T)>` | contravariant in `T` | "I consume `T` values" |
| `PhantomData<fn() -> T>` | covariant in `T` | "I produce `T` values" |
| `PhantomData<fn(T) -> T>` | invariant in `T` | Both consume and produce |
| `PhantomData<*const T>` | covariant in `T` | Raw pointer, read-only |
| `PhantomData<*mut T>` | invariant in `T` | Raw pointer, mutable |
Choosing a marker
Start from what the struct means, not from the variance you want. Then check that the variance follows.
Owning through a raw pointer
A raw pointer carries no ownership information. NonNull<T> is covariant in T, but the compiler does not know the struct frees a T on drop. Adding PhantomData<T> states that ownership, and the drop checker uses it to reject code where T would already be gone when drop runs.
use std::marker::PhantomData;
use std::ptr::NonNull;
struct Owned<T> {
ptr: NonNull<T>,
_owns: PhantomData<T>,
}
impl<T> Owned<T> {
fn new(value: T) -> Self {
let ptr = NonNull::from(Box::leak(Box::new(value)));
Owned { ptr, _owns: PhantomData }
}
fn get(&self) -> &T {
// SAFETY: `ptr` came from a leaked Box and is freed only in `drop`.
unsafe { self.ptr.as_ref() }
}
}
impl<T> Drop for Owned<T> {
fn drop(&mut self) {
// SAFETY: `ptr` was created from `Box::leak` and is dropped once.
unsafe { drop(Box::from_raw(self.ptr.as_ptr())) }
}
}
fn main() {
let text = String::from("borrowed");
let owned: Owned<&str> = Owned::new(text.as_str());
println!("{}", owned.get());
}Owned<T> is covariant in T because NonNull<T> and PhantomData<T> both are. This matches how Vec<T> and Box<T> behave. Had you used *mut T, the struct would be invariant, and an Owned<&'static str> could not be used where an Owned<&'a str> is expected.
Forcing invariance: lifetime branding
Sometimes you want the compiler to refuse to shrink a lifetime. If two values must belong to the same container, you can give each container a unique lifetime "brand". Invariance stops the compiler from merging two brands into one shorter lifetime.
use std::cell::Cell;
use std::marker::PhantomData;
type Brand<'id> = PhantomData<Cell<&'id ()>>;
struct Checked<'id, T> {
items: Vec<T>,
_brand: Brand<'id>,
}
struct Idx<'id> {
i: usize,
_brand: Brand<'id>,
}
impl<'id, T> Checked<'id, T> {
fn check(&self, i: usize) -> Option<Idx<'id>> {
(i < self.items.len()).then(|| Idx { i, _brand: PhantomData })
}
fn get(&self, idx: Idx<'id>) -> &T {
// No bounds check needed: `idx` was validated against this container.
&self.items[idx.i]
}
}
fn with_checked<T, R>(items: Vec<T>, f: impl for<'id> FnOnce(Checked<'id, T>) -> R) -> R {
f(Checked { items, _brand: PhantomData })
}
fn main() {
with_checked(vec![10, 20, 30], |a| {
with_checked(vec!["x", "y"], |b| {
let i = a.check(2).unwrap();
println!("{}", a.get(i));
// println!("{}", b.get(i)); // error: lifetime may not live long enough
let j = b.check(1).unwrap();
println!("{}", b.get(j));
})
});
}The for<'id> bound means the closure must work for any 'id, so each call to with_checked creates a fresh, unnamed brand. The index i has the brand of a. If Brand were covariant, the compiler could shrink both brands to a common lifetime and b.get(i) would compile. Because Cell<&'id ()> is invariant, the two brands stay distinct and the commented line is rejected. This combines the invariance and higher-ranked bounds you have already seen.
Checking the result
You can test a variance choice without running anything. Write a function that tries to shrink the lifetime and see whether it compiles.
use std::marker::PhantomData;
struct Reader<'a>(PhantomData<&'a ()>);
fn shrink<'long: 'short, 'short>(x: Reader<'long>) -> Reader<'short> {
x
}
fn main() {
let r: Reader<'static> = Reader(PhantomData);
let _s = shrink(r);
}Replace the marker with PhantomData<Cell<&'a ()>> (and add the Cell import) and shrink stops compiling. Library authors keep tests like this so a refactor cannot silently change a public type's variance. A variance change is a breaking change for users.
Exercise
A type Sink<T> never stores a T. It only has a method fn push(&self, value: T) that forwards values elsewhere. Which PhantomData marker describes it best, and what variance does Sink<T> get in T?
Show answer
Use PhantomData<fn(T)>. A function that takes T is contravariant in T, so Sink<T> is contravariant. A Sink<&'short str> can then be replaced by a Sink<&'long str>, because a sink that accepts short-lived strings also accepts long-lived ones.
Exercise
You change the field _marker: PhantomData<&'a T> to _marker: PhantomData<&'a mut T> in a public struct View<'a, T>. What changes for users, and why is this a breaking change?
Show answer
View stays covariant in 'a but becomes invariant in T. Code that relied on shrinking T (for example a View<'a, &'static str> passed where a View<'a, &'b str> is expected) no longer compiles. Because existing user code can stop compiling, the change is breaking.