Sub topic 3
PhantomData: telling the compiler you use T
This chapter assumes you know generic structs, trait bounds, and how to read a compiler error. Earlier chapters covered zero-sized types. Here you will see why Rust rejects an unused type parameter and how PhantomData fixes that.
The unused parameter error
Suppose you want a type that carries a tag, such as which kind of record an ID refers to. The tag is only for the type checker, so no field needs to hold it.
struct Id<T> {
raw: u64,
}
fn main() {
let _id: Id<String> = Id { raw: 1 };
}This fails with error E0392: parameter T is never used. The compiler needs to know how T relates to the struct. That relationship decides whether Id<&'long str> can be used where Id<&'short str> is expected (variance). It also decides whether the struct owns a T when it is dropped, and whether the struct is Send or Sync. With no field mentioning T, the compiler has nothing to infer these from, so it refuses to guess.
The fix
std::marker::PhantomData<T> is a zero-sized type. Adding a field of that type tells the compiler how your struct relates to T, and no data is stored.
use std::marker::PhantomData;
use std::mem::size_of;
struct Id<T> {
raw: u64,
_marker: PhantomData<T>,
}
fn main() {
println!("PhantomData<String>: {} bytes", size_of::<PhantomData<String>>());
println!("Id<String>: {} bytes", size_of::<Id<String>>());
println!("u64: {} bytes", size_of::<u64>());
let id: Id<String> = Id { raw: 1, _marker: PhantomData };
println!("{}", id.raw);
}The output shows 0, 8, and 8 bytes. The marker adds nothing to the layout. You create a value by writing PhantomData, with no arguments, and the compiler infers T from the field's type.
What the marker tells the compiler
The form you choose inside PhantomData<...> sets three properties of your struct:
- Variance: how substituting a longer-lived or more specific type for
Tis treated. - Drop check: whether dropping your struct may drop a
T. - Auto traits: whether
SendandSyncdepend onT.
PhantomData<T> behaves as if the struct owned a T. That is correct for a struct that really holds T through a raw pointer. It is often too strong for a pure tag, because the struct then inherits T's Send and Sync status. A later chapter compares the alternatives, such as PhantomData<fn() -> T>. For now, use PhantomData<T> and know that it makes a claim of ownership.
Derives need care
#[derive(Clone)] on Id<T> generates impl<T: Clone> Clone for Id<T>. The bound is on T, even though the struct stores only a u64. An Id<Connection> would then be non-cloneable if Connection is not Clone. Write the impl by hand to avoid the extra bound:
use std::marker::PhantomData;
struct Id<T> {
raw: u64,
_marker: PhantomData<T>,
}
impl<T> Clone for Id<T> {
fn clone(&self) -> Self {
*self
}
}
impl<T> Copy for Id<T> {}
struct Connection; // not Clone
fn main() {
let a: Id<Connection> = Id { raw: 5, _marker: PhantomData };
let b = a;
let c = a.clone();
println!("{} {}", b.raw, c.raw);
}Common mistakes
- Writing
PhantomData<T>as a value with turbofish, such asPhantomData::<T>, works but is rarely needed. PlainPhantomDatainfers the type. - Adding a real
Tfield "just to use it" costs memory and forces callers to supply a value. - Forgetting that
PhantomData<T>makes the struct!SendwhenTis!Send.
Exercise
Why does struct Tag<T> { raw: u64 } fail to compile, and what is the smallest change that fixes it without increasing the struct's size?
Show answer
The compiler cannot determine variance, drop-check behavior, or auto-trait behavior for a parameter that no field uses (error E0392). Add a field _marker: PhantomData<T> (importing std::marker::PhantomData). PhantomData<T> is zero-sized, so size_of::<Tag<T>>() stays 8 bytes.