PhantomData for zero-cost type-level markers

Marcus Chen Jan 2026
1 tab
use std::marker::PhantomData;

struct Token<'a> {
    _marker: PhantomData<&'a ()>,
}

impl<'a> Token<'a> {
    fn new() -> Self {
        Token { _marker: PhantomData }
    }
}
1 file · rust Explain with highlit

PhantomData<T> is a zero-sized type that acts as if it owns T for the purposes of lifetimes, variance, and drop check. I use it in the typestate pattern or when a struct logically depends on T but doesn't store it. For example, a handle to an external resource might have PhantomData<&'a Resource> to tie its lifetime. It affects compilation but compiles to nothing. The generic parameter prevents unused type parameter errors. It's a low-level tool mostly used in advanced generic or unsafe code. Understanding PhantomData helps when writing generic libraries that need precise lifetime or ownership semantics.