Sub topic 15
PhantomData and marker types
This chapter assumes you can write generic structs and impl<T> blocks, and that you know what zero-sized types are. It shows how to give a type a parameter that exists only for the compiler.
The problem: a parameter with no field
Suppose you want a Length type that remembers its unit, so the compiler can stop you from adding meters to feet. The natural design is a type parameter U for the unit. But the value is just an f64, and nothing in the struct needs a U.
Rust rejects a struct that declares a type parameter and never uses it. The compiler reports error E0392, "parameter U is never used". It needs to know how U relates to the data, for example whether the struct owns a U, because that affects drop checking, variance, and auto traits such as Send.
PhantomData as the fix
std::marker::PhantomData<U> is a zero-sized type. It stores nothing at runtime, but it tells the compiler that the struct is tied to U. A type parameter used only this way is called a marker (or phantom) type.
use std::marker::PhantomData;
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 Length<Meters> {
fn to_feet(self) -> Length<Feet> {
Length::new(self.value * 3.28084)
}
}
fn add<U>(a: Length<U>, b: Length<U>) -> Length<U> {
Length::new(a.value + b.value)
}
fn main() {
let a: Length<Meters> = Length::new(1.0);
let b: Length<Meters> = Length::new(2.5);
let total = add(a, b);
println!("{} m", total.value);
let feet = total.to_feet();
println!("{:.2} ft", feet.value);
println!("{}", std::mem::size_of::<Length<Meters>>());
}Meters and Feet are empty structs. They are never constructed. They exist only as labels. The program prints 3.5 m, 11.48 ft, and 8. The last number shows that PhantomData adds no bytes beyond the f64.
What the compiler enforces
add requires both arguments to share the same U. Calling add(meters, feet) is a compile error, with no runtime check and no runtime cost. The specialized impl Length<Meters> block, which you saw in an earlier chapter, makes to_feet available only for meters.
Common uses
- Units and states. Marker types can encode a unit, or the state of an object such as
Door<Open>andDoor<Closed>, where only valid transitions exist as methods. - Typed IDs.
Id<User>andId<Order>can both wrap au64without being interchangeable. - Unsafe code. Types that hold a raw pointer use
PhantomData<T>to say they logically own or borrow aT.
Common mistakes
- Forgetting
PhantomDataand getting E0392. - Writing
unit: Uinstead ofPhantomData<U>. That forces you to build a realUvalue, which is awkward for empty marker types. - Writing
PhantomDatawith no type in a struct literal and getting an inference error. Annotate the type or let a function signature fix it. - Expecting marker types to need trait bounds. They need none unless you add behavior through traits.
Exercise
You define struct Id<T> { raw: u64 } and the compiler reports that parameter T is never used. How do you fix it, and what stops an Id<User> from being passed where an Id<Order> is expected?
Show answer
Add a field marker: PhantomData<T> and set it to PhantomData in the constructor. Id<User> and Id<Order> are then different types, so the compiler rejects passing one where the other is expected. The field takes no space at runtime.