Skip to main content

PhantomData

The standard-library marker that lets a type carry a type parameter without storing a value of it. It makes zero-sized providers and type-level markers legal, and it is the value you pass to give a function a type instead of data.

Overview​

In Context-Generic Programming (CGP), PhantomData is a standard-library type, not a CGP type. It comes from core::marker. It has a page here because it appears throughout CGP code and does one specific job. A reader who has only seen it as noise in a struct definition will misread much of what CGP generates.

CGP uses it for declaring a type that is generic over something it never stores, and for passing a type to a function as a zero-sized value. The sections below work through both uses.

Why a marker needs it​

Rust requires a type to use every generic parameter it declares, in a field or in a bound. A type-level marker conflicts with that rule by design. It is generic over a parameter without storing a value of it, because the parameter is part of the type's identity rather than its data.

A provider is the clearest case. Multiply<Field> stores nothing at run time, yet it must be generic over Field so that the wiring can tell one instance from another. Written as a plain unit struct, it does not compile:

pub struct Multiply<Field>;
// error[E0392]: type parameter `Field` is never used

PhantomData<Field> is the fix. It is a zero-sized field that tells the compiler to treat the type as though it holds a Field, so the parameter counts as used and the struct stays empty at run time:

use core::marker::PhantomData;

pub struct Multiply<Field>(pub PhantomData<Field>);

Multiply<u32> and Multiply<u64> are now distinct types the wiring can choose between, and the struct is still zero-sized.

Definition​

PhantomData is a zero-sized unit-like struct with one type parameter:

pub struct PhantomData<T: ?Sized>;

That definition has the shape the previous section said the compiler rejects: a struct generic over a T that it stores nowhere. PhantomData compiles anyway because the compiler knows it. It carries a #[lang = "phantom_data"] attribute that the compiler recognizes, so it alone is exempt from the unused-parameter rule, and every other marker type can use it. Those types satisfy the rule by holding a PhantomData field rather than by being one.

The parameter is ?Sized, so T may be any type, sized or not. A value of PhantomData<T> is zero-sized and holds nothing. Its only content is the type T, recorded in its own type. You construct one by writing PhantomData. Where inference cannot supply the type, you name it with a turbofish, as in PhantomData::<u32>. CGP re-exports it through the prelude, so use cgp::prelude::*; brings it into scope.

PhantomData<T> also tells the compiler how the surrounding type relates to T, beyond satisfying the used-parameter rule. It sets variance (whether a longer lifetime may stand in for a shorter one), drop checking, and the auto traits such as Send and Sync. Most CGP markers do not depend on which relationship they get, so they use the plain PhantomData<T>. Life is the exception. It wraps its lifetime as PhantomData<*mut &'a ()>, which makes it invariant in the lifetime and neither Send nor Sync. That page explains the consequences.

How CGP uses it​

The declaring side and the passing side look different in the code.

On the declaring side, PhantomData fills the field of a zero-sized type, the way Multiply<Field> above carries it. The same pattern runs through CGP's recursive type-level lists: a Chars node holds its next node in a PhantomData<Tail>, a PathCons holds both its head and tail that way, and a Field holds its type-level name tag in a PhantomData<Tag> beside the one real value it stores. In each case the parameter is part of the type's identity, and the type does not keep a value of it at run time.

On the passing side, PhantomData::<T> is a zero-sized value that passes the type T to a function. A method that must know which field, which computation, or which tag is meant takes a PhantomData<T> argument, and the caller supplies the type through it:

// which field to read:
let name = self.get_field(PhantomData::<Symbol!("name")>);

// which computation to run:
let output = context.compute(PhantomData::<Doubled>, input);

Here the context is the type the method runs on, which supplies the values it needs as its fields. The PhantomData argument carries nothing. It exists so that type inference selects the right HasField impl or the right handler. The call passes a type where a value is expected, and PhantomData::<T> is the empty value that stands for the type T.

You rarely write either role yourself, because a higher-level construct produces each for you.

  • On the declaring side, the new keyword of #[cgp_impl] declares the provider struct: a bare struct Foo; when the provider lacks generic parameters, and otherwise one PhantomData field over the parameter, or over a tuple of all of them when there are several, with each lifetime wrapped as Life<'a>.
  • On the passing side, #[implicit] and #[cgp_auto_getter] read a context field without the tag, so your code does not contain a get_field(PhantomData::<...>) call.

You meet PhantomData directly only when you work below these constructs.

Examples​

A provider generic over the field it reads uses PhantomData on both sides. new declares the struct with a PhantomData<Tag> field, and the body passes the tag to get_field as PhantomData::<Tag>:

use cgp::core::field::traits::HasField;
use cgp::prelude::*;

#[cgp_component(Greeter)]
pub trait CanGreet {
fn greet(&self) -> String;
}

// `new` declares `pub struct GreetField<Tag>(pub PhantomData<Tag>);`
#[cgp_impl(new GreetField<Tag>)]
#[uses(HasField<Tag, Value = String>)]
impl<Tag> Greeter {
fn greet(&self) -> String {
let name = self.get_field(PhantomData::<Tag>);
format!("Hello, {name}!")
}
}

#[derive(HasField)]
pub struct Person {
pub name: String,
}

delegate_components! {
Person {
GreeterComponent: GreetField<Symbol!("name")>,
}
}

check_components! {
Person {
GreeterComponent,
}
}

// A marker over two parameters holds one `PhantomData` over a tuple.
pub struct Add<Left, Right>(pub PhantomData<(Left, Right)>);

pub fn demo() {
let person = Person {
name: "World".to_owned(),
};
assert_eq!(person.greet(), "Hello, World!");

// Both markers occupy no space.
assert_eq!(core::mem::size_of::<GreetField<Symbol!("name")>>(), 0);
assert_eq!(core::mem::size_of::<Add<u32, String>>(), 0);
}

Person is a value context, and CanGreet is self-targeted: the greeting reads the person it is called on. The wiring names the tag once, in GreetField<Symbol!("name")>, and the provider carries it as a type. The idiomatic way to read a field of the context is an #[implicit] argument, which hides the tag. GreetField passes the tag explicitly because the field it reads is a parameter chosen by the wiring.

When to use it​

You write PhantomData yourself only to declare a marker field or to pass a type at a call site. Everywhere else the macros insert it for you.

  • Declare a PhantomData field when you write a zero-sized struct that is generic over a type without storing a value of it, such as a provider struct you define yourself rather than through #[cgp_new_provider]. One PhantomData over a tuple covers several parameters.
  • Pass PhantomData::<T> at a call site that takes a type-level selector, such as get_field or a handler's compute. This is the common case you write yourself, and the turbofish names the type when inference cannot.
  • Hold a lifetime as PhantomData<Life<'a>> to match what #[cgp_new_provider] declares for a lifetime parameter. A plain PhantomData<&'a ()> also satisfies the unused-parameter rule, but it is covariant in 'a and keeps the struct Send and Sync, where the macro's form is invariant and neither.

Common Mistakes​

It costs nothing at run time. PhantomData<T> is zero-sized whatever T is, so a struct full of PhantomData fields is still zero-sized, and a PhantomData argument compiles to nothing. A PhantomData in a signature does not mean a hidden allocation.

Leaving the tag to inference fails when nothing fixes it. In a struct field the type comes from the field's declared type, so plain PhantomData is enough. At a call site the turbofish states it. A get_field call on a context with two fields cannot infer which one is meant:

#[derive(HasField)]
pub struct Person {
pub name: String,
pub age: u8,
}

pub fn print_name(person: &Person) {
let name = person.get_field(PhantomData);
println!("{name}");
}

The compiler reports two errors, headed error[E0284]: type annotations needed and error[E0283]: type annotations needed, and the second names the cause:

note: multiple `impl`s satisfying `Person: cgp::macro_prelude::HasField<_>` found

Write PhantomData::<Symbol!("name")> to name the field.

A generic marker needs its PhantomData field, for a lifetime as much as for a type. A struct that is generic over a T without storing a value of it fails with error[E0392], as the first section shows. The same rule covers a lifetime parameter: pub struct Borrowing<'a>; fails with error[E0392]: lifetime parameter `'a` is never used, and a PhantomData<Life<'a>> field fixes it.

  • Field: holds its type-level name tag in a PhantomData<Tag> beside its value.
  • Life: a lifetime lifted into a type through a deliberately invariant PhantomData.
  • Chars and PathCons: recursive type-level lists whose tails are PhantomData markers.
  • Symbol! and Index: the tags a PhantomData::<Tag> argument usually carries.
  • HasField: whose get_field takes the tag as a PhantomData argument.
  • #[cgp_new_provider]: declares a provider struct's PhantomData field for you.

The ideas behind it:

Source​

  • The type is standard-library: core::marker::PhantomData, whose documentation covers the variance, drop-check, and auto-trait effects in full.
  • CGP re-exports it through the prelude, so use cgp::prelude::*; brings PhantomData into scope alongside the rest.
  • The provider struct new declares, with its PhantomData field: empty_struct.rs

An AI agent wrote this page using the CGP knowledge base. Its content was verified against the library's source. See How AI is used in this project.