Sub topic 4
Marker types as compile-time labels
This chapter assumes you know Rust generics, trait bounds and impl blocks. It also assumes you have seen PhantomData<T> as the fix for an unused type parameter. Here you use it to attach a label to a value.
What a marker type is
A marker type is a type you define only so its name can be used as a label. It holds no data and has no methods. Its only job is to be a type argument.
struct Meters;
struct Feet;Each is a unit struct, so it takes no space. Length<Meters> and Length<Feet> are two different types, even though both come from one generic definition. The compiler treats them as unrelated, so it can refuse to mix them.
A worked example: units of length
The struct stores a plain f64. The Unit parameter appears only inside PhantomData.
use std::marker::PhantomData;
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 {
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<Meters> = Length::new(3.5);
let total = a + b;
println!("{} m", total.value);
let f: Length<Feet> = Length::new(10.0);
println!("{:.3} m", f.to_meters().value);
// let bad = total + f; // error: expected `Length<Meters>`, found `Length<Feet>`
}Three things happen here:
Addis written once, generically. Its signature takesSelf, so both operands must carry the same label.to_meterslives inimpl Length<Feet>. It exists only for feet, and the next chapters build on this.- The label is never read at runtime. It exists only while the compiler checks types.
Choosing the shape of a marker
Unit structs are the usual choice. You can also write an empty enum.
enum Meters {}An empty enum has no values, so nobody can create one by accident. That fits a label that should never be a value. Because PhantomData needs no value of Unit, both forms work. Pick one and use it consistently.
| Form | Can be constructed | Typical use |
|---|---|---|
| `struct Meters;` | Yes, as `Meters` | Labels that may also be passed as values |
| `enum Meters {}` | No | Labels used only as type arguments |
Common errors
Unused parameter. If you leave out _unit: PhantomData<Unit>, the compiler reports error E0392 ("type parameter Unit is never used"). Add the field.
Derives that demand too much. #[derive(Clone)] on Length<Unit> generates impl<Unit: Clone> Clone for Length<Unit>. Meters does not implement Clone, so Length<Meters> would not be cloneable, even though it only holds an f64. Write the impls by hand without the bound:
use std::marker::PhantomData;
struct Meters;
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<Meters> = Length { value: 1.5, _unit: PhantomData };
let b = a;
println!("{} {}", a.value, b.value);
println!("{}", std::mem::size_of::<Length<Meters>>());
}This prints 1.5 1.5 and then 8, so the marker adds no bytes. The same applies to Debug, PartialEq and similar derives. If you want them on a phantom-tagged type, implement them manually or accept the bound on the marker.
Exercise
You add #[derive(Clone, Copy)] to Length<Unit> and then copy a Length<Meters> where Meters is a plain unit struct with no derives. Why does the compiler reject the copy, and how do you fix it?
Show answer
The derive generates impl<Unit: Clone> Clone and impl<Unit: Copy> Copy, which require Meters to implement Clone and Copy. Fix it either by deriving Clone, Copy on Meters too, or by writing impl<Unit> Clone for Length<Unit> and impl<Unit> Copy for Length<Unit> by hand, so no bound is placed on the marker.