liveBook · Manning

PhantomData

As explained in Idiomatic Rust

PhantomData is a Rust standard-library zero-sized marker struct that logically associates a type with a generic parameter or ownership relationship without storing a value of that type.

`PhantomData` is a zero-sized marker struct for a relationship that matters to Rust’s type system but does not require a stored value. A generic struct can use it to carry a type parameter: `Dog<Breed>` can distinguish breeds at compile time while storing only the dog’s name. Without a field using `Breed`, the compiler reports that the parameter is unused. section 2.1.5

Make a generic parameter count

```rust use std::marker::PhantomData; struct Poodle {} struct Dog<Breed> { name: String, breed: PhantomData<Breed>, } let dog: Dog<Poodle> = Dog { name: "Jeffrey".into(), breed: PhantomData, }; ``` The field must be initialized, but it stores no `Poodle` value. The annotation `Dog<Poodle>` supplies the concrete type for the marker. section 2.1.5

The type tag can select behavior without adding breed state. For example, `impl Dog<Poodle> { fn breed_name(&self) -> &str { "poodle" } }` defines a method for that concrete type. Other breeds can have their own `impl` blocks; a missing specialization is caught when code tries to call its absent method. Use `impl Dog<Poodle>`, not `impl<Breed> Dog<Breed>`, when the behavior is breed-specific. section 2.1.5

A phantom field can also record a lifetime. An iterator with `phantom: PhantomData<&'a T>` carries `'a` in its type even though the field holds no reference. In the linked-list iterator example, this accompanies pointer-backed state used to return references. That implementation also requires `unsafe`; adding `PhantomData` is not a substitute for making those references valid. section 3.2.4

How Idiomatic Rust covers it

How deep it goes
Works through an unused-generic compiler error, construction, and concrete implementations; also shows a lifetime-bearing iterator, without developing PhantomData’s broader internals.
Examples
Shows breed-tagged dogs, an unused-parameter compiler error, specialized `breed_name()` methods, and a linked-list iterator carrying `PhantomData<&'a T>`.
What it assumes
Assumes familiarity with Rust structs and generics; motivates the marker through a compiler error and explains lifetimes alongside the iterator example.
What you can do after
Build it from scratch: add a phantom field to a generic struct or capture a lifetime in an iterator type.
How it connects
Connects generic parameters and concrete implementations with marker structs, and connects iterator lifetimes with references and borrow checking.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Idiomatic Rust. The section links point to the parts of the book it draws on.