skip to content

In a Rust typestate request builder, why does `RequestBuilder<S>` need a `PhantomData<S>` field, and what does that field cost at run time?

level: middleimportance: should knowfreq 28%

answer

  1. unused type parameter
  2. E0392
  3. zero bytes, alignment 1
  4. derive adds bounds on S

basics

~20 s

Rust rejects a struct whose type parameter appears in no field, error E0392. PhantomData<S> is that use; it is zero-sized, so RequestBuilder<NoUrl> is exactly as large as its real fields and the marker costs nothing at run time.

solid answer

~40 s

In a typestate builder the state, such as `NoUrl` or `HasUrl`, is only a type argument; no field holds a value of it. rustc refuses a struct with an unused type parameter, E0392, and its help suggests "a marker such as `PhantomData`". `PhantomData<S>` tells the compiler the type acts as if it held an `S` without storing one. std guarantees `size_of::<PhantomData<T>>() == 0` and alignment 1 for every `T`, and the state types are unit structs or empty enums, which are zero-sized too. So `RequestBuilder<NoUrl>` and `RequestBuilder<HasUrl>` have the same size as the real fields, and changing state copies no extra bytes. One catch: `#[derive(Clone)]` then requires `S: Clone`.

code

rust · 20 lines
rust
use std::marker::PhantomData;

struct NoUrl;
struct HasUrl;

#[allow(dead_code)]
struct RequestBuilder<S> {
    url: Option<String>,
    headers: Vec<(String, String)>,
    _state: PhantomData<S>,
}

fn main() {
    println!("NoUrl: {}", size_of::<NoUrl>());
    println!("PhantomData<HasUrl>: {}", size_of::<PhantomData<HasUrl>>());
    println!("PhantomData<String>: {}", size_of::<PhantomData<String>>());
    println!("fields without the marker: {}", size_of::<(Option<String>, Vec<(String, String)>)>());
    println!("RequestBuilder<NoUrl>: {}", size_of::<RequestBuilder<NoUrl>>());
    println!("RequestBuilder<HasUrl>: {}", size_of::<RequestBuilder<HasUrl>>());
}

go deeper

for a junior

Recall that PhantomData marks a type parameter as used without storing anything, and that it takes zero bytes.

for a middle

Explain E0392, why the state types are zero-sized, and why a state transition copies no extra data.

for a senior

Choose between unit-struct, empty-enum and data-carrying states, and handle the extra S bounds that derives add to a generic builder.

for a principal

Set a convention for marker types in shared libraries, including which derives state types carry so builders stay cloneable and printable.

## The problem PhantomData solves A **typestate** builder encodes its state in a type parameter: `RequestBuilder<NoUrl>` before a URL is set, `RequestBuilder<HasUrl>` after. The state types carry no data; they exist only to select which `impl` blocks apply. That creates a problem, because the struct never stores an `S`: ```rust struct RequestBuilder<S> { url: Option<String>, } ``` rustc rejects this with **E0392**, "type parameter `S` is never used", and its help line reads: "consider removing `S`, referring to it in a field, or using a marker such as `PhantomData`". Rust insists every type parameter be used, because a parameter's uses decide how the type behaves with respect to lifetimes and subtyping (its variance), auto traits such as `Send`, and the drop checker. Those details belong to the material on variance and on threads; for typestate the point is simpler: the compiler needs a field that mentions `S`. ## What PhantomData is `std::marker::PhantomData<T>` is a unit-like struct in `core::marker`. Its documentation says adding a `PhantomData<T>` field "tells the compiler that your type acts as though it stores a value of type `T`, even though it doesn't really". You write the field's type as `PhantomData<S>` and construct it with the bare value `PhantomData`: ```rust use std::marker::PhantomData; struct RequestBuilder<S> { url: Option<String>, headers: Vec<(String, String)>, _state: PhantomData<S>, } ``` The leading underscore on `_state` is a naming convention, not a requirement. ## What it costs: nothing **Zero-sized types** (ZSTs) occupy no memory. The relevant ones here: - `PhantomData<T>` for **any** `T`: the docs guarantee `size_of::<PhantomData<T>>() == 0` and `align_of::<PhantomData<T>>() == 1`, even for `PhantomData<String>`. - **Unit structs** such as `struct NoUrl;`, which have no fields. - **Empty enums** such as `enum HasUrl {}`, which have no values at all. Because the marker adds no size and its alignment of 1 never raises the struct's alignment, `RequestBuilder<NoUrl>` and `RequestBuilder<HasUrl>` are exactly the size of `(Option<String>, Vec<(String, String)>)`, 48 bytes on a 64-bit target. A transition such as `url(self, ...) -> RequestBuilder<HasUrl>` moves the same fields into a new struct with a different type argument; the state change itself copies nothing. The Rustonomicon puts the general rule this way: Rust "largely understands that any operation that produces or stores a ZST can be reduced to a no-op". ## Choosing the marker | State marker | Can be stored as a field? | Size | When to use | |---|---|---|---| | `struct NoUrl;` (unit struct) | yes, `state: S` works | 0 | states that may carry data later | | `enum NoUrl {}` (empty enum) | no value exists | 0 | pure markers nobody should construct | | `struct HasUrl(String);` | yes, holds data | size of the data | the state owns what it proves | 1. With unit structs you could store `state: S` instead of `PhantomData<S>`; it is still zero bytes. 2. With empty enums only `PhantomData<S>` works, since no value of `S` can ever exist, which also stops anyone from building a state value by accident. 3. When the state should own data, such as the URL itself, a data-carrying state removes the `Option` from the builder. ## The derive trap `#[derive(Clone)]` on a generic struct adds a bound on every type parameter: the generated impl is `impl<S: Clone> Clone for RequestBuilder<S>`. That bound is added even though `PhantomData<S>` itself implements `Clone` and `Copy` for every `S`. So cloning a `RequestBuilder<NoUrl>` whose `NoUrl` is not `Clone` fails with **E0599**, and rustc's note says "trait bound `NoUrl: Clone` was not satisfied", suggesting "consider manually implementing the trait to avoid undesired bounds". Two fixes: - Derive `Clone` (and `Copy`, `Debug` where wanted) on the state types themselves. - Or write `impl<S> Clone for RequestBuilder<S>` by hand, cloning the real fields and writing `_state: PhantomData`. ## Things that are not true - PhantomData does not hold a hidden `S`, a pointer, or a type tag; nothing of `S` exists at run time. - An unused type parameter is not a warning to silence; it is a hard error, E0392. - Each state does not need its own copy of the builder's fields; one generic struct serves all states.

  • Could the builder store `state: S` instead of `PhantomData<S>`?
    Yes, when the states are unit structs: `state: NoUrl` is still zero bytes and each transition writes `state: HasUrl`. It does not work with empty-enum states, because no value exists to store. A state can also carry data, such as `struct HasUrl(String)`, which removes the builder's `Option` around the URL.
  • Why does adding `#[derive(Debug)]` to the builder sometimes make `{:?}` fail to compile?
    Like `Clone`, the derive adds `S: Debug` to the generated impl, so a state type that does not implement `Debug` makes the builder's `Debug` impl unusable. Derive `Debug` on the state types too, or implement `Debug` for the builder by hand without the bound.

  • PhantomData stores a hidden copy or pointer of S for later use
  • Each state marker adds at least one byte to the builder
  • An unused type parameter only produces a warning you can allow
  • PhantomData<S> implements Clone only when S implements Clone
  • Every state needs its own struct with the builder's fields copied in