liveBook · Manning

Phantom type

As explained in Idiomatic Rust

A type-system technique that attaches a generic parameter to a type without storing a value of that parameter.

A phantom type lets a Rust struct carry type information without storing a value of that type. Use it when the distinction matters at compile time, such as tagging a dog with its breed without adding breed data to the struct. section 2.1.5

use std::marker::PhantomData;

struct Dog<Breed> {
    name: String,
    breed: PhantomData<Breed>,
}

Add a PhantomData field to use the generic parameter and satisfy the compiler. Construction still requires a PhantomData value; the marker is optimized out at compile time. section 2.1.5

impl Dog<Labrador> {                    #1
    fn breed_name(&self) -> &str {
        "labrador"        #2
    }
}
impl Dog<Retriever> {
    fn breed_name(&self) -> &str {
        "retriever"
    }
}
impl Dog<Poodle> {
    fn breed_name(&self) -> &str {
        "poodle"
    }
}
impl Dog<Dachshund> {
    fn breed_name(&self) -> &str {
        "dachshund"
    }
}

Distinct breed types allow separate Dog implementations, so each type can return its breed name without storing that name as state. section 2.1.5

How Idiomatic Rust covers it

How deep it goes
Works through the unused-parameter error, PhantomData, construction, and specialized implementations.
Examples
Uses a Dog tagged with empty breed types, including a Poodle named Jeffrey.
What you can do after
Build it from scratch by adding PhantomData and defining type-specific Dog implementations.
How it connects
Connects phantom types to marker structs, marker traits, and struct tagging.

Also explained in

Compare how 2 books explain phantom type →

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.