Sub topic 15
PhantomData and Marker Types
This chapter assumes you can write generic structs and impl blocks, know what a trait bound is, and understand ownership and references. It covers how to use a type parameter that no field stores, and why you would want to.
The problem: a parameter nothing uses
Sometimes a type should carry information at compile time that has no runtime value. Examples are the unit of a measurement or the state of a protocol. A type parameter is the natural tool, but Rust rejects a parameter that no field uses.
std::marker::PhantomData<T> is the fix. It is a zero-sized type: it takes no memory, and it has one value, also written PhantomData. Adding a PhantomData<U> field tells the compiler that the struct is related to U, and nothing is stored at runtime.
use std::marker::PhantomData;
fn main() {
println!("{}", std::mem::size_of::<PhantomData<String>>());
println!("{}", std::mem::size_of::<PhantomData<[u8; 1024]>>());
}Both lines print 0, whatever type is inside the brackets.
Marker types
A marker type is a type that exists only to be used as a type argument. Usually it is an empty struct:
struct Meters;
struct Feet;These have no fields and no methods. They are never meant to hold data. They are labels that the type checker can tell apart. Because Meters and Feet are different types, Length<Meters> and Length<Feet> are different types too, even though both contain one f64.
An empty enum with no variants also works as a marker, and nobody can construct a value of it by accident. Unit structs are more common in practice and easier to use in tests.
Worked example: units that cannot be mixed
This program tags a length with its unit. Adding two lengths with the same unit works. Adding different units does not compile.
use std::marker::PhantomData;
use std::ops::Add;
struct Meters;
struct Feet;
struct Length<U> {
value: f64,
unit: PhantomData<U>,
}
impl<U> Length<U> {
fn new(value: f64) -> Self {
Length { value, unit: PhantomData }
}
}
impl<U> Clone for Length<U> {
fn clone(&self) -> Self {
Length::new(self.value)
}
}
impl<U> Copy for Length<U> {}
impl<U> Add for Length<U> {
type Output = Length<U>;
fn add(self, rhs: Length<U>) -> Length<U> {
Length::new(self.value + rhs.value)
}
}
impl Length<Feet> {
fn to_meters(self) -> Length<Meters> {
Length::new(self.value * 0.3048)
}
}
fn main() {
let a: Length<Meters> = Length::new(1.0);
let b: Length<Feet> = Length::new(10.0);
let doubled = a + a;
let total = a + b.to_meters();
println!("{:.3}", doubled.value);
println!("{:.3}", total.value);
// let wrong = a + b; // error: expected `Length<Meters>`, found `Length<Feet>`
}It prints 2.000 and 4.048.
Three details matter here:
to_metersis defined in animpl Length<Feet>block, so it exists only for feet. This is the specialized impl pattern from earlier in the tutorial, applied to a marker.Addis implemented once for allU. Therhs: Length<U>parameter forces both sides to share the same unit.- Conversion is the only way to move from
Length<Feet>toLength<Meters>, so the compiler enforces that you convert.
Why `Clone` and `Copy` are written by hand
Writing #[derive(Clone, Copy)] on Length<U> is a common mistake. A derive adds a bound on every type parameter, so it would produce impl<U: Clone> Clone for Length<U>. Meters does not implement Clone, so Length<Meters> would not be cloneable or copyable, and a + a above would fail with a "use of moved value" error.
The manual impls have no bound on U. PhantomData<U> is Copy and Clone for every U, so nothing needs to be required. The alternative is to derive Clone, Copy on the marker structs as well. That works but spreads the requirement to every marker you ever write.
The same applies to Debug, PartialEq, Default, and Hash. Derives add U: Trait bounds. If the marker type does not meet them, write the impl yourself.
Typestate: encoding a state machine in types
The typestate pattern uses a marker parameter to represent the state of a value. Methods are available only in states where they make sense. Transitions consume self and return a value with a different marker.
use std::marker::PhantomData;
struct Open;
struct Closed;
struct Door<State> {
name: String,
_state: PhantomData<State>,
}
impl Door<Closed> {
fn new(name: &str) -> Self {
Door { name: name.to_string(), _state: PhantomData }
}
fn open(self) -> Door<Open> {
println!("{} opens", self.name);
Door { name: self.name, _state: PhantomData }
}
}
impl Door<Open> {
fn close(self) -> Door<Closed> {
println!("{} closes", self.name);
Door { name: self.name, _state: PhantomData }
}
}
fn main() {
let door = Door::new("front door");
let door = door.open();
let door = door.close();
println!("{} is closed", door.name);
// door.close(); // error: no method named `close` found for `Door<Closed>`
}Because open takes self by value, the old Door<Closed> is moved and cannot be used again. Invalid sequences, such as closing a closed door, are compile errors instead of runtime checks. The cost is zero at runtime. The trade-off is that the state is fixed at compile time, so a door whose state is only known at runtime (read from a file, say) needs an enum wrapping the variants.
PhantomData and lifetimes
PhantomData also solves the unused-lifetime version of the problem. This matters when a struct holds a raw pointer, which carries no lifetime information of its own.
use std::marker::PhantomData;
struct RawSlice<'a, T> {
ptr: *const T,
len: usize,
_borrow: PhantomData<&'a [T]>,
}
impl<'a, T> RawSlice<'a, T> {
fn new(slice: &'a [T]) -> Self {
RawSlice {
ptr: slice.as_ptr(),
len: slice.len(),
_borrow: PhantomData,
}
}
fn get(&self, index: usize) -> Option<&T> {
if index < self.len {
// Safe: index is in bounds and the data outlives 'a.
Some(unsafe { &*self.ptr.add(index) })
} else {
None
}
}
}
fn main() {
let data = vec![1, 2, 3];
let raw = RawSlice::new(&data);
println!("{:?}", raw.get(1));
println!("{:?}", raw.get(7));
}It prints Some(2) and None. The PhantomData<&'a [T]> field makes RawSlice behave as if it borrowed a slice for 'a. The borrow checker then refuses to let data be dropped or mutated while a RawSlice is alive.
What the PhantomData argument controls
The type inside PhantomData<...> is not arbitrary. It tells the compiler how to treat the struct for variance, drop checking, and auto traits (Send and Sync). The choice matters when the struct is unsafe or low-level.
| Field | Behaves as if the struct... | `Send` / `Sync` |
|---|---|---|
| `PhantomData<T>` | owns a `T` | follow `T` |
| `PhantomData<&'a T>` | borrows a `T` for `'a` | follow `&T` |
| `PhantomData<fn() -> T>` | only produces a `T`, owns none | always `Send` and `Sync` |
| `PhantomData<*const T>` | holds a raw pointer to `T` | neither `Send` nor `Sync` |
For plain marker types like Meters, PhantomData<U> is fine, because the marker is an empty struct that is trivially Send and Sync. The choice matters when the parameter is a real type and the struct is meant to be used from other threads. If you want a tag that never affects thread safety, PhantomData<fn() -> T> is a common choice. Also, PhantomData<T> makes the drop checker assume the struct may drop a T. That is correct for a custom container and unnecessarily strict for a pure tag.
Common errors
- E0392, parameter never used. Add a
PhantomData<T>field. UsePhantomData<&'a T>for lifetimes. - Forgetting to write
PhantomDatain the constructor. The field needs a value:unit: PhantomData. The type is inferred from the struct definition. - Derived traits that demand
U: Trait. Write manual impls, as withCloneabove. - Methods defined on every state. If
openis inimpl<S> Door<S>, it is callable on an open door. Put each method in an impl for the specific marker. - Using
PhantomDatawhen a real field would do. If the struct already stores aT, no marker is needed.
Exercise
You add #[derive(Clone)] to struct Length<U> { value: f64, unit: PhantomData<U> }. Meters is a unit struct with no derives. Why does calling .clone() on a Length<Meters> fail to compile, and how do you fix it without changing Meters?
Show answer
The derive generates impl<U: Clone> Clone for Length<U>, so Length<Meters> is Clone only if Meters is. Fix it by writing the impl by hand with no bound on U: impl<U> Clone for Length<U> { fn clone(&self) -> Self { Length::new(self.value) } }. Adding #[derive(Clone)] to Meters would also work, but every marker would then need it.
Exercise
In the Door example, what happens if you add fn open(self) -> Door<Open> to impl<S> Door<S> instead of impl Door<Closed>, and what do you lose?
Show answer
It compiles, and open becomes callable on a door that is already open. You lose the compile-time guarantee that a door can only be opened from the closed state, which is the purpose of the typestate pattern.