Sub topic 11
Choosing PhantomData<T>, PhantomData<fn() -> T> and friends
This chapter assumes you know Rust generics, trait bounds, lifetimes at the level of 'a annotations, and how PhantomData and marker types are used in typed IDs and typestate code. For typestate markers the choice of PhantomData form rarely matters. It matters for tagged values that cross threads, for types that hold borrowed or raw data, and for public library types.
What PhantomData actually decides
PhantomData<X> is a zero-sized type. It adds no bytes at runtime, but it makes the compiler treat your struct as if it contained an X. That choice affects three things:
- Variance: whether
Handle<&'static str>can be used whereHandle<&'a str>is expected, or the reverse. - Drop check: whether the compiler assumes dropping your struct may drop a
T. - Auto traits: whether
SendandSyncfor your struct depend onT.
Writing PhantomData<T> makes all three behave as if the struct owned a T. Often that is not what you mean. A typed ID tagged Order does not own an Order.
The common forms
| Form | Variance | Drop check treats struct as owning `T` | `Send` / `Sync` |
|---|---|---|---|
| `PhantomData<T>` | covariant in `T` | yes | same as `T` |
| `PhantomData<fn() -> T>` | covariant in `T` | no | always both |
| `PhantomData<fn(T)>` | contravariant in `T` | no | always both |
| `PhantomData<fn(T) -> T>` | invariant in `T` | no | always both |
| `PhantomData<*const T>` | covariant in `T` | no | neither |
| `PhantomData<*mut T>` | invariant in `T` | no | neither |
| `PhantomData<&'a T>` | covariant in `'a` and `T` | no | `Send` and `Sync` need `T: Sync` |
| `PhantomData<&'a mut T>` | covariant in `'a`, invariant in `T` | no | follows `T` |
| `PhantomData<Cell<T>>` | invariant in `T` | yes | `Send` if `T: Send`, never `Sync` |
Function pointer types are always Send and Sync, whatever their argument or return types are. That is why fn() -> T is the usual choice for a pure tag.
Auto traits: the tag should not infect the struct
Auto traits such as Send and Sync are implemented for a struct automatically when all its fields have them. If a tag type is not thread-safe, PhantomData<T> makes the whole struct not thread-safe, even though no T exists at runtime.
use std::marker::PhantomData;
use std::rc::Rc;
struct Owning<T> {
_m: PhantomData<T>,
}
struct Tag<T> {
_m: PhantomData<fn() -> T>,
}
fn assert_send<X: Send>() {}
fn assert_sync<X: Sync>() {}
fn main() {
assert_send::<Tag<Rc<()>>>();
assert_sync::<Tag<Rc<()>>>();
assert_send::<Owning<String>>();
// assert_send::<Owning<Rc<()>>>(); // error: `Rc<()>` cannot be sent between threads safely
println!("checks passed");
}Tag<Rc<()>> is Send and Sync because it holds only a function pointer type. Owning<Rc<()>> is not Send, because the compiler follows PhantomData<T> to Rc<()>.
In real code, a tag is usually a unit struct such as struct User;, which is already Send and Sync. The difference shows up when the tag is generic over a type you do not control, for example Id<Rc<Widget>> or Id<MutexGuard<'_, T>>.
Variance: which substitutions the compiler allows
Variance describes how subtyping on a parameter carries over to the generic type. The only subtyping Rust has is between lifetimes: &'static str can be used where &'a str is expected, because 'static outlives 'a.
- Covariant:
Wrapper<&'static str>is usable asWrapper<&'a str>. Most read-only types behave this way. - Contravariant: the reverse.
fn(&'a str)is usable wherefn(&'static str)is expected. This is rare. - Invariant: no substitution. The lifetime must match exactly.
You can see the difference by writing a function that shortens a lifetime.
use std::marker::PhantomData;
struct Covariant<T> {
_m: PhantomData<fn() -> T>,
}
struct Invariant<T> {
_m: PhantomData<fn(T) -> T>,
}
fn shorten<'a>(x: Covariant<&'static str>) -> Covariant<&'a str> {
x
}
// fn shorten_inv<'a>(x: Invariant<&'static str>) -> Invariant<&'a str> {
// x // error: lifetime may not live long enough
// }
fn main() {
let c: Covariant<&'static str> = Covariant { _m: PhantomData };
let _short = shorten(c);
let _i: Invariant<&'static str> = Invariant { _m: PhantomData };
println!("ok");
}For typed IDs and typestate markers, covariance is the harmless default. Choose invariance when your type could be used to write through a reference. For example, a struct that stores a *mut T must be invariant in T. If it were covariant, safe code could store a short-lived value into a slot that is later read as a longer-lived one.
Drop check: owning versus tagging
Drop check is the compiler's rule for deciding which values must still be alive when a struct is dropped. If a struct might drop a T, then T and everything it borrows must be valid at that moment. PhantomData<T> tells the compiler "this struct owns a T and may drop it." PhantomData<fn() -> T> does not.
In everyday safe code you will rarely see the difference. A struct that has no Drop impl and no field mentioning T imposes no constraint either way. The distinction matters in unsafe collection code. For example, a vector-like type that holds a *mut T and frees its buffer in Drop should declare PhantomData<T>, so the compiler knows the elements are dropped along with it.
Which form to pick
The question to ask is: does this struct own, borrow, or merely label a T?
In practice:
- Tag only (typed IDs, typestate markers, units of measure): use
PhantomData<fn() -> T>. It adds noSendorSyncconstraints and imposes no drop-check ownership. - Owns data through a raw pointer: use
PhantomData<T>next to the*mut Tfield. Auto traits and drop check then followT, which is correct for a container. - Borrows data through a raw pointer: use
PhantomData<&'a T>orPhantomData<&'a mut T>. Iterator types commonly do this, so the lifetime'ais tied to the borrow. - Need invariance: use
PhantomData<fn(T) -> T>for a pure tag, orPhantomData<*mut T>if you also want the type to be notSendand notSync. - Need a type that is deliberately not thread-safe: add
PhantomData<*const ()>orPhantomData<Rc<()>>, depending on whether you want it to be!Sendand!Syncor just clear intent.
The next-to-last case is an easy one to get wrong. Never use PhantomData<*const T> merely to avoid owning T. It removes Send and Sync from your struct, which will surprise users who try to share an ID across threads.
A gotcha with derives on tagged types
#[derive(Clone, Copy, PartialEq)] adds a bound T: Clone, T: Copy or T: PartialEq on each type parameter, even if T appears only inside PhantomData. With Id<User>, that means User itself would need to implement Copy, which is not what you want for an empty tag type. Implement the traits by hand so they depend only on the raw value.
use std::marker::PhantomData;
struct Id<T> {
raw: u64,
_m: PhantomData<fn() -> T>,
}
impl<T> Clone for Id<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for Id<T> {}
impl<T> PartialEq for Id<T> {
fn eq(&self, other: &Self) -> bool {
self.raw == other.raw
}
}
struct User; // no derives needed on the tag
fn main() {
let a: Id<User> = Id { raw: 1, _m: PhantomData };
let b = a; // Copy: `a` is still usable
println!("{}", a == b);
}This works because the manual impls say Id<T> is Copy for every T, with no bound on T. Crates such as derivative and derive-where can generate the same impls with custom bounds, if you prefer not to write them.
Common mistakes
- Using
PhantomData<T>for a pure tag. The type becomes!SendwheneverTis!Send. Switch toPhantomData<fn() -> T>. - Using
PhantomData<*const T>for a pure tag. The type is always!Sendand!Sync. - Using
PhantomData<T>instead of an owning field. If you hold a raw pointer to heap data you free inDrop, you needPhantomData<T>so drop check and auto traits are correct. A tag-only form lies to the compiler here. - Forgetting that
fn() -> Trequires nothing ofT. It does not constrainT: 'staticorT: Sizedthe way a stored value would, so add those bounds yourself if your API needs them. - Deriving traits on tagged types. See the previous section.
Summary of the decision
For safe, tag-only types, which covers the typed IDs and typestate structs from earlier chapters, PhantomData<fn() -> T> is a good default. It is covariant, always Send and Sync, and does not claim to own a T. When your struct really owns, borrows, or writes through T, pick the form that says so. The right choice usually follows directly from asking whether the struct owns, borrows or only labels T.
Exercise
A library defines struct Handle<T> { id: u32, _m: PhantomData<T> } and users report that Handle<Rc<Config>> cannot be sent to another thread, even though a handle holds only a u32. Which PhantomData form fixes this, and why does it work? What would you check before changing it?
Show answer
Change the field to PhantomData<fn() -> T>. Function pointer types are always Send and Sync, so Handle<T> no longer inherits the thread-safety of T. Before changing it, check that the type does not actually own or free a T (for example through a raw pointer in a Drop impl). If it did, PhantomData<T> would be correct and the thread-safety restriction would be intended.
Exercise
Why does #[derive(Clone, Copy)] on struct Id<T> { raw: u64, _m: PhantomData<fn() -> T> } make Id<User> unusable as Copy when User is a plain unit struct with no derives, and how do you fix it?
Show answer
The derive adds the bounds T: Clone and T: Copy, so Id<User> is Copy only if User is. Fix it by writing impl<T> Clone for Id<T> { fn clone(&self) -> Self { *self } } and impl<T> Copy for Id<T> {} by hand, which put no bounds on T.