Sub topic 11
Choosing PhantomData<T>, PhantomData<fn() -> T> and friends
This chapter assumes you know generic structs, the PhantomData marker from earlier chapters, and basic lifetimes. Until now we wrote PhantomData<T> without thinking about it. For typestate markers like Open and Closed that is fine. For generic tags such as Id<T>, the form you pick changes which auto traits your type has.
What the choice controls
PhantomData<X> makes the compiler treat your struct as if it contained a field of type X. That affects three properties:
- Variance. Whether
Wrapper<&'long str>can be used whereWrapper<&'short str>is expected. - Auto traits. Whether
SendandSynchold for your type. - Drop check. Whether the compiler assumes your type may drop a
Twhen it is dropped.
For a type that only uses T as a label, you usually want no ownership and no thread-safety restrictions inherited from T.
The common forms
| Form | Variance in `T` | `Send` / `Sync` | Drop check assumes it owns a `T` |
|---|---|---|---|
| `PhantomData<T>` | covariant | same as `T` | yes |
| `PhantomData<fn() -> T>` | covariant | always both | no |
| `PhantomData<fn(T)>` | contravariant | always both | no |
| `PhantomData<fn(T) -> T>` | invariant | always both | no |
| `PhantomData<*const T>` | covariant | neither | no |
Function pointer types are Send and Sync no matter what T is. That makes them a convenient way to say "I mention T but hold no data of that type."
Seeing the difference
Compare two tagged types, one using PhantomData<T> and one using PhantomData<fn() -> T>. assert_send is a function that compiles only for Send types.
use std::marker::PhantomData;
use std::rc::Rc;
struct Owned<T> {
_marker: PhantomData<T>,
}
struct Tag<T> {
_marker: PhantomData<fn() -> T>,
}
fn assert_send<X: Send>() {}
fn main() {
assert_send::<Tag<Rc<()>>>();
// assert_send::<Owned<Rc<()>>>(); // error: `Rc<()>` cannot be sent between threads safely
let _t: Tag<String> = Tag { _marker: PhantomData };
let _o: Owned<String> = Owned { _marker: PhantomData };
println!("Tag is Send for any T; Owned<T> is Send only if T is");
}Rc<()> is not Send, so Owned<Rc<()>> is not either. Tag<Rc<()>> is Send because it never stores an Rc. If your type really is only a label, the second behavior is the accurate one.
Choosing a form
Use these rules in order:
- The type owns or may drop a
T. This is the case for a raw-pointer container that allocatesTvalues. UsePhantomData<T>, so drop check and auto traits followT. - The type borrows data. Use
PhantomData<&'a T>(or&'a mut T) so the lifetime is tracked. - The type only labels something with
T. This covers typed IDs and handles. UsePhantomData<fn() -> T>. Tmust not be substituted with a longer or shorter lifetime. This matters whenTcontains lifetimes that must match exactly. Use an invariant form such asPhantomData<fn(T) -> T>.- The type must not cross threads whatever
Tis. Use a pointer form such asPhantomData<*const T>.
Common mistakes
- Using
PhantomData<T>for a pure tag. AnId<Rc<Thing>>silently losesSend, and the error shows up far from the definition. - Using
PhantomData<*const T>for a tag. This removesSendandSyncfor everyT, which is rarely what you want. - Assuming variance does not matter. If
Tcan contain a lifetime, covariance may let callers shorten it in ways your API did not intend. Pick an invariant form when that would be unsound or surprising. - Forgetting that the marker is a field. You still need to write
_marker: PhantomDatain every constructor.
Exercise
You are defining Handle<T>, a typed index into a table that is shared across threads. T is only a label, and some T values are Rc-based types that are not Send. Which PhantomData form should the _marker field use, and why not PhantomData<T>?
Show answer
Use PhantomData<fn() -> T>. Function pointer types are always Send and Sync, so Handle<T> stays thread-safe for every T. PhantomData<T> would make Handle<Rc<...>> non-Send, because the compiler would treat the handle as owning a T, even though it stores only an index.