Sub topic 1
Rust Phantom Types and the Typestate Pattern
Prerequisites
This chapter assumes Rust ownership, structs, impl blocks, generic types, and basic compiler errors.
Generic types and the unused parameter error
A generic type has one or more type parameters, such as T in struct Boxed<T>. Rust requires each type parameter to affect the struct's definition.
struct Boxed<T> {
value: u64,
}This definition fails because T is declared but never used. The compiler cannot determine how T relates to Boxed<T>. It also cannot correctly reason about properties such as variance, ownership, or automatic traits.
Zero-sized types: types that take no space
A zero-sized type (ZST) is a type whose values need no storage. An empty struct is a ZST:
struct User;
struct Order;A User value and an Order value take zero bytes. Although they have no runtime data, their different types can carry useful compile-time information. They can act as labels.
PhantomData: telling the compiler you use T
PhantomData<T> is a zero-sized value that tells Rust that a struct is related to T. It lets a generic parameter participate in the type without adding data to each value.
use std::marker::PhantomData;
use std::mem::size_of;
struct User;
struct Order;
struct Id<T> {
raw: u64,
_tag: PhantomData<T>,
}
impl<T> Id<T> {
fn new(raw: u64) -> Self {
Self {
raw,
_tag: PhantomData,
}
}
}
fn load_user(id: Id<User>) -> u64 {
id.raw
}
fn main() {
let user_id = Id::<User>::new(10);
let order_id = Id::<Order>::new(10);
println!("{}", load_user(user_id));
println!("Id<User>: {} bytes", size_of::<Id<User>>());
println!("Id<Order>: {} bytes", size_of::<Id<Order>>());
let _ = order_id;
}Both ID types have the same runtime size as one u64. However, Id<User> and Id<Order> are different, incompatible types.
Marker types as compile-time labels
A marker type is usually an empty type used only as a type-level label. The label can prevent accidental mixing without runtime checks.
This pattern is the foundation for typestate APIs. Later, different marker types will represent states, and methods will be available only for the appropriate state.
Exercise
Why does adding PhantomData<T> solve the unused type parameter error without increasing the size of Id<T>?
Show answer
PhantomData<T> uses T in the type definition, while PhantomData itself is zero-sized, so the compiler receives the type relationship without storing a T value.