liveBook · Manning

Marker struct

As explained in Idiomatic Rust

A struct, typically with no meaningful data, that marks a type with compile-time information.

Marker structs let a generic type carry compile-time information without storing that information as state. In Rust, `PhantomData` marks an otherwise unused generic parameter; empty types can then distinguish concrete specializations. section 2.1.5

use std::marker::PhantomData;

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

Add `PhantomData<Breed>` so the compiler accepts the generic parameter without storing a breed value. 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"
    }
}

Concrete implementations specialize `Dog` for each marker type and provide breed-specific methods. section 2.1.5

How Idiomatic Rust covers it

How deep it goes
Works through an unused-generic compiler error, adds `PhantomData`, and demonstrates concrete specialized implementations.
Examples
Uses empty breed structs and `Dog<Breed>` implementations that return breed names.
What you can do after
Apply Rust generics and `PhantomData` to distinguish types at compile time and define specialized methods.
How it connects
Connects generic types with `PhantomData` and concrete type-specific implementations.

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.