Sub topic 3
PhantomData: telling the compiler you use T
This chapter assumes you know Rust ownership and borrowing, generic structs with trait bounds, and how to read a compiler error. You don't need to know variance or unsafe. Where they matter, the chapter explains them.
The error: a type parameter that is never used
Suppose you want a typed ID: a u64 that remembers at compile time which kind of thing it identifies. The obvious attempt is a generic struct:
struct Id<T> { raw: u64 }
Rust rejects it:
error[E0392]: type parameter `T` is never used
--> src/main.rs:1:11
|
1 | struct Id<T> {
| ^ unused type parameter
|
= help: consider removing `T`, referring to it in a field, or using a marker such as `PhantomData`The rule can look pedantic, but the compiler has a reason for it. A type parameter must appear in the struct's fields because the compiler derives three facts about the struct from the fields:
- Variance. Whether
Id<&'long str>can be used whereId<&'short str>is expected. The compiler reads this from howTappears in the fields. With no field mentioningT, it has nothing to read. - Drop check. Whether dropping an
Id<T>might drop aT, and therefore whether the dataTborrows must still be alive. - Auto traits. Whether
SendandSynchold. They normally follow from the field types.
Rust refuses to guess these facts. It makes you state them. PhantomData is how you state them.
The fix: a field that costs nothing
std::marker::PhantomData<T> is a zero-sized type. It occupies no memory, but to the compiler it behaves as if the struct had a field related to T. Add one field and the error goes away:
use std::marker::PhantomData;
use std::mem::size_of;
struct Id<T> {
raw: u64,
_marker: PhantomData<T>,
}
struct User;
struct Order;
fn main() {
let user: Id<User> = Id { raw: 1, _marker: PhantomData };
let order: Id<Order> = Id { raw: 1, _marker: PhantomData };
// The tag adds no bytes.
assert_eq!(size_of::<Id<User>>(), size_of::<u64>());
println!("{} {}", user.raw, order.raw);
}PhantomData is also a value. The expression PhantomData has the type PhantomData<_>, and inference fills in T from the field type. You rarely write PhantomData::<T> by hand.
Two details are worth knowing:
- The field name starts with an underscore by convention. It is never read, and the underscore silences the unused-field warning.
PhantomData<T>has size 0 and alignment 1. It never changes a struct's size or padding.Id<User>andId<Order>are both 8 bytes.
If T may be an unsized type such as str or dyn Trait, declare struct Id<T: ?Sized>. PhantomData<T> accepts unsized T.
A reference to what the parameter means
PhantomData<T> is not a magic "ignore this parameter" marker. It tells the compiler to treat the struct as if it owned a T. If your type holds a raw pointer, the compiler can't see a borrow or an owner behind it, so the marker has to say what the pointer stands for.
Lifetime parameters have the same unused-parameter rule. This type is a minimal view into a slice, built on a raw pointer:
use std::marker::PhantomData;
struct Slice<'a, T> {
ptr: *const T,
len: usize,
_borrow: PhantomData<&'a T>,
}
impl<'a, T> Slice<'a, T> {
fn new(data: &'a [T]) -> Self {
Slice { ptr: data.as_ptr(), len: data.len(), _borrow: PhantomData }
}
fn get(&self, i: usize) -> Option<&T> {
if i < self.len {
// SAFETY: `i < len`, and `'a` keeps the original slice alive.
Some(unsafe { &*self.ptr.add(i) })
} else {
None
}
}
}
fn main() {
let v = vec![10, 20, 30];
let s = Slice::new(&v);
println!("{:?}", s.get(1));
// drop(v); // error: cannot move out of `v` because it is borrowed
println!("{:?}", s.get(2));
}*const T carries no lifetime, so without PhantomData<&'a T> the 'a parameter would be unused and rejected. With the marker, the borrow checker treats Slice as holding a shared borrow of the data for 'a. If you uncomment the drop(v) line, the program stops compiling. The compiler is protecting the unsafe code.
Choosing the form of the marker
PhantomData<T> is the default, but it is not neutral. It says "this type owns a T", and that choice affects variance, drop check, and auto traits. Other forms say something different:
| Marker | Variance in `T` | Drop check acts as if it owns a `T` | `Send` / `Sync` |
|---|---|---|---|
| `PhantomData<T>` | covariant | yes | follow `T` |
| `PhantomData<&'a T>` | covariant | no | follow `&T` |
| `PhantomData<*const T>` | covariant | no | neither |
| `PhantomData<fn() -> T>` | covariant | no | always both |
| `PhantomData<fn(T)>` | contravariant | no | always both |
| `PhantomData<fn(T) -> T>` | invariant | no | always both |
Covariant means a Wrapper<&'long X> can stand in for a Wrapper<&'short X>. Invariant means no such substitution is allowed. For a pure tag, covariance is usually harmless.
The practical rule for tags is this. If your type only labels T and never stores one, prefer PhantomData<fn() -> T>. It has no ownership claim and no thread-safety side effects. If your type really does own T through a pointer, use PhantomData<T> so drop check sees the ownership. The chapter on variance and auto traits returns to this choice. Here you only need to know it exists and that the default is a claim of ownership.
The derive gotcha
A common mistake is writing #[derive(Clone, Copy, PartialEq)] on Id<T>. A derive adds a bound on every type parameter, so the generated code reads impl<T: Clone> Clone for Id<T>. The marker type User is not Clone, so Id<User> isn't Clone either, even though the struct holds only a u64. The error appears at the call site, which makes it confusing.
PhantomData<T> itself implements Clone, Copy, PartialEq, Eq, Hash, Default and more for any T, with no bound. Implement the traits 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> {}
impl<T> PartialEq for Id<T> {
fn eq(&self, other: &Self) -> bool {
self.raw == other.raw
}
}
struct User;
fn show(id: Id<User>) -> u64 {
id.raw
}
fn main() {
let a: Id<User> = Id { raw: 5, _marker: PhantomData };
let b = a; // copies, because Id<User> is Copy
println!("{} {}", show(a), show(b));
println!("{}", a == b);
}clone can return *self because Copy is implemented in the next line. No T: Clone bound appears anywhere, so User needs no derives.
Common errors
- Using
PhantomDatawith the wrong type argument.PhantomData<u64>inId<T>does not mentionT, so E0392 stays. The argument must involve the parameter. - Expecting runtime data.
PhantomDatastores nothing. You cannot read aTback from it. Code that needs the tag at runtime needs an associated constant or trait method on the marker type, which later chapters cover. - Using
PhantomData<T>as a pure tag with a non-Sendtype. IfTisRc<()>, a struct holdingPhantomData<T>stops beingSend, even though it holds noRc. - Forgetting that both sides must agree.
Id<User>andId<Order>are different types. A function taking one will not accept the other, and that is the point. To convert between them you must write the conversion explicitly.
Exercise
A struct Tagged<T> { value: u32, _m: PhantomData<T> } is created as Tagged<Rc<()>> and sent to another thread with std::thread::spawn. The compiler rejects it. Why, and how do you change the struct so the program compiles?
Show answer
PhantomData<T> makes Send follow T, and Rc<()> is not Send, so Tagged<Rc<()>> is not Send either, even though no Rc is stored. Change the marker to PhantomData<fn() -> T>. A function pointer type is always Send and Sync, and T still appears in the struct, so the unused-parameter error does not return.
Exercise
You write #[derive(Clone, Copy)] struct Id<T> { raw: u64, _m: PhantomData<T> } and struct Order;. Why does let b = id_of_order; let c = id_of_order; fail with a move error, and what is the fix?
Show answer
The derives generate impl<T: Clone> Clone and impl<T: Copy> Copy. Order implements neither, so Id<Order> is not Copy and the first let moves the value. The fix is to write impl<T> Clone for Id<T> { fn clone(&self) -> Self { *self } } and impl<T> Copy for Id<T> {} by hand, with no bound on T. Deriving Clone and Copy on Order would also work, but it forces that requirement on every marker type.