Sub topic 4
Marker types as compile-time labels
This chapter assumes you know Rust generics and trait bounds, and that you have seen PhantomData<T> used to satisfy the "parameter is never used" error. Here we look at the other half of the pairing: the types you put inside PhantomData. These are marker types, and they act as labels the compiler checks.
What a marker type is
A marker type exists only to be named. It has no fields and no methods, and you rarely create a value of it. You use it as a type argument, so the compiler can tell Length<Meters> apart from Length<Feet>.
struct Meters;
struct Feet;Each of these is a unit struct, which is a struct with no fields. A unit struct is a zero-sized type: size_of::<Meters>() is 0. A struct that holds PhantomData<Meters> therefore takes the same space as the same struct without the label.
The compiler never writes the label to memory, so it costs nothing at runtime. The label does change type identity. Length<Meters> and Length<Feet> are two unrelated types, and the compiler will not convert one into the other unless you write the conversion.
A first labelled type
This program labels a length with its unit. Adding two lengths is allowed only when the labels match.
use std::marker::PhantomData;
use std::mem::size_of;
use std::ops::Add;
struct Meters;
struct Feet;
struct Length<Unit> {
value: f64,
_unit: PhantomData<Unit>,
}
impl<Unit> Length<Unit> {
fn new(value: f64) -> Self {
Length { value, _unit: PhantomData }
}
}
impl<Unit> Add for Length<Unit> {
type Output = Length<Unit>;
fn add(self, other: Self) -> Self::Output {
Length::new(self.value + other.value)
}
}
impl Length<Feet> {
fn to_meters(self) -> Length<Meters> {
Length::new(self.value * 0.3048)
}
}
fn main() {
let a: Length<Meters> = Length::new(2.0);
let b: Length<Feet> = Length::new(10.0);
// let wrong = a + b; // error: mismatched types, expected `Length<Meters>`
let total = a + b.to_meters();
println!("{:.3} m", total.value);
println!("same size as f64: {}", size_of::<Length<Meters>>() == size_of::<f64>());
}The program prints 5.048 m and then same size as f64: true.
The Add impl uses a single Unit for both sides, so mixing units is a type error. The to_meters method sits in an impl Length<Feet> block, so it exists only for feet. Later chapters build the typestate pattern on this same technique.
Unit struct or empty enum
You can declare a marker in two ways.
struct Imperial; // unit struct: a value can be written as `Imperial`
enum Metric {} // empty enum: no value of this type can existAn empty enum has no variants, so nobody can construct a value of it. The compiler enforces "this type is only a label." A unit struct can be constructed, which is harmless but unnecessary. The empty enum is also zero-sized.
| Form | Can you build a value? | Typical use |
|---|---|---|
| `struct Tag;` | Yes, by writing `Tag` | Labels that are sometimes also passed as values, such as a state you hand to a function |
| `enum Tag {}` | No | Labels used only as type arguments |
| `struct Tag<T>(PhantomData<T>)` | Yes | Labels that are themselves generic (rare) |
Most Rust code uses unit structs because they are shorter, and because some patterns do need a value of the marker. The standard library's Global allocator and many crates' Open/Closed states follow this style. Choose the empty enum when you want to rule out a value of the marker type.
The derive trap
#[derive(Clone)] on a generic struct adds a bound on every type parameter. For Length<Unit>, the derive generates impl<Unit: Clone> Clone for Length<Unit>. If your marker does not implement Clone, then Length<Marker> is not Clone either, even though the marker contributes no data.
An empty enum such as Metric has this problem unless you also derive Clone on it. The same applies to Copy, Debug, PartialEq, Default, and Hash.
You can avoid this in two ways. You can derive the traits on every marker, or you can write the impls by hand without the bound on the label:
use std::marker::PhantomData;
enum Metric {}
struct Imperial;
struct Length<Unit> {
value: f64,
_unit: PhantomData<Unit>,
}
impl<Unit> Clone for Length<Unit> {
fn clone(&self) -> Self {
*self
}
}
impl<Unit> Copy for Length<Unit> {}
fn main() {
let a: Length<Metric> = Length { value: 1.5, _unit: PhantomData };
let b = a; // copies, because Length<Metric> is Copy
println!("{} {}", a.value, b.value);
let c: Length<Imperial> = Length { value: 4.0, _unit: PhantomData };
let d = c.clone();
println!("{} {}", c.value, d.value);
}Neither Metric nor Imperial implements Clone or Copy, yet Length is Copy for both. The hand-written impls place no bound on Unit, which is correct because the label contributes nothing to copy.
Attaching data to a label with a trait
A bare marker tells the compiler which type you mean, but it carries no information the program can read. To get runtime information such as a name or a conversion factor, give the markers a shared trait and use associated constants.
use std::fmt;
use std::marker::PhantomData;
trait Unit {
const SYMBOL: &'static str;
const PER_METER: f64;
}
struct Meters;
struct Feet;
impl Unit for Meters {
const SYMBOL: &'static str = "m";
const PER_METER: f64 = 1.0;
}
impl Unit for Feet {
const SYMBOL: &'static str = "ft";
const PER_METER: f64 = 3.28084;
}
struct Length<U> {
value: f64,
_unit: PhantomData<U>,
}
impl<U: Unit> Length<U> {
fn new(value: f64) -> Self {
Length { value, _unit: PhantomData }
}
fn convert<V: Unit>(self) -> Length<V> {
Length::new(self.value / U::PER_METER * V::PER_METER)
}
}
impl<U: Unit> fmt::Display for Length<U> {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
write!(f, "{:.2} {}", self.value, U::SYMBOL)
}
}
fn main() {
let run: Length<Meters> = Length::new(100.0);
let in_feet: Length<Feet> = run.convert();
println!("{in_feet}");
}This prints 328.08 ft. The expression U::SYMBOL is resolved at compile time. The compiler generates a separate copy of fmt for each unit, with the constant already substituted. The marker is still never stored, and the label is turned into data only through the trait.
Notice the bound U: Unit sits on the impl blocks and not on the struct. Putting it on the struct would force every mention of Length<T> to repeat the bound, including in code that does nothing with units. Put bounds where the behavior is.
Choosing a form
The decision comes down to two questions: does the program need to read anything from the label, and should anyone be able to construct it?
A trait is also the right tool when you need to limit which types can be used as a label, since a bound like U: Unit rejects Length<String>. Without a bound, any type is accepted as a label, including nonsensical ones such as Length<i32>. A later chapter shows how to close the set of labels completely with a sealed trait.
Common errors
- Forgetting that a marker is not a value.
Length<Meters>stores noMeters. If you need a value to pass around, such as a configuration object, make a real field. A marker is for the type system only. - Using a marker with fields.
struct Tag(u32);is not zero-sized, so aPhantomData<Tag>still costs nothing, but a storedTagcosts four bytes. Keep markers empty when the goal is zero cost. - Expecting a runtime branch on the label. You cannot write
if U == Metersin a generic function. The label is a type, not a value. Use a trait with an associated constant or method instead. - Over-bounded derives. As shown above,
#[derive(Clone)]can silently make a labelled type non-Clone. When a method says "the traitCloneis not implemented forMarker," this is usually the cause. - Reusing one marker for different meanings. A
Metersmarker in a length module and aMetersmarker in an altitude module are different types if declared twice, but the same type if shared. Share markers deliberately.
Exercise
A struct Tagged<T> { id: u32, _t: PhantomData<T> } derives Clone and Copy. You declare enum Admin {} and use Tagged<Admin>. Calling .clone() fails to compile. Why, and what are two ways to fix it?
Show answer
The derive generates impl<T: Clone> Clone for Tagged<T>, so Tagged<Admin> is Clone only if Admin is. Admin does not implement Clone. Fix it by adding #[derive(Clone, Copy)] to Admin, or by writing impl<T> Clone for Tagged<T> and impl<T> Copy for Tagged<T> by hand without a bound on T.
Exercise
You need markers Celsius and Fahrenheit, and a generic Display impl that prints the degree symbol and letter for each. Which marker form do you use, and where does the bound go?
Show answer
Use unit structs that implement a shared trait with an associated constant, such as const SUFFIX: &'static str. Put the bound on the impl<U: Scale> fmt::Display for Temperature<U> block rather than on the struct definition, so the struct itself stays usable without the trait.