In Rust, a `Handle<'arena>` holding only a `u32` index fails with E0392 - which `PhantomData` field fixes it, and how does that choice set variance?
answer
- an unused parameter rustc refuses
- a zero-sized stand-in field
- act as if it held a shared borrow
- the marker's type decides variance and auto traits
basics
~20 sAdd a zero-sized PhantomData field that mentions 'arena. PhantomData<&'arena Arena> makes the handle behave like a shared borrow: covariant in 'arena and tied to the arena. PhantomData<Cell<&'arena ()>> or PhantomData<fn(&'arena ()) -> &'arena ()> would make it invariant.
solid answer
~40 srustc rejects a lifetime or type parameter no field uses with E0392 ("lifetime parameter `'arena` is never used"), because it could not compute the parameter's variance or bounds. `std::marker::PhantomData<T>` is a zero-sized field that tells the compiler to treat the struct as if it stored a `T` for variance, auto traits and drop check. For a handle that borrows an arena, `PhantomData<&'arena Arena>` is the honest choice: covariant in `'arena`, `Send`/`Sync` exactly when `&Arena` is, and the handle keeps the arena borrowed, so `insert(&mut self)` while a handle is live fails with E0502. Choosing `PhantomData<Cell<&'arena ()>>` or `PhantomData<fn(&'arena ()) -> &'arena ()>` makes `'arena` invariant; the `Cell` form also makes the handle `!Sync`, and `PhantomData<*const &'arena ()>` makes it neither `Send` nor `Sync`.
code
rust · 33 linesuse std::marker::PhantomData;
struct Arena {
items: Vec<String>,
}
#[derive(Clone, Copy)]
struct Handle<'arena> {
index: u32,
_arena: PhantomData<&'arena Arena>,
}
impl Arena {
fn insert(&mut self, s: &str) -> u32 {
self.items.push(s.to_owned());
(self.items.len() - 1) as u32
}
fn handle(&self, index: u32) -> Handle<'_> {
Handle { index, _arena: PhantomData }
}
fn get(&self, h: Handle<'_>) -> &str {
&self.items[h.index as usize]
}
}
fn main() {
let mut arena = Arena { items: Vec::new() };
let i = arena.insert("player");
let h = arena.handle(i);
println!("{} size={}", arena.get(h), std::mem::size_of::<Handle<'_>>());
// arena.insert("enemy"); // E0502 while `h` is still used below
println!("{}", h.index);
}go deeper
Recall that rustc refuses a declared lifetime or type parameter that no field uses, and that PhantomData is the zero-sized field that fixes it.
Explain that PhantomData makes the struct act as if it held the named type for variance and auto traits, and show PhantomData<&'a T> as the borrow-like default.
Pick the marker deliberately: covariant borrow form, invariant fn(&'a ()) -> &'a () or Cell forms, and the Send/Sync side effects of Cell and raw-pointer markers.
Treat the marker as part of the public contract: changing it changes variance and auto traits, which can break downstream callers just as changing a real field would.
## Why rustc rejects an unused parameter A handle into an arena often stores nothing but an index: `struct Handle<'arena> { index: u32 }`. The `'arena` is there so that a handle cannot outlive, or be used against, the arena that issued it. rustc 1.99.1 refuses the definition with `error[E0392]: lifetime parameter `'arena` is never used` and suggests "referring to it in a field, or using a marker such as `PhantomData`". The reason is that a struct's **variance** and implied bounds are computed from its fields. A parameter that appears in no field has no variance at all, and because unbounded parameters historically caused trouble, they are forbidden in struct definitions. ## What `PhantomData` simulates `std::marker::PhantomData<T>` is a unit-like struct the compiler knows about. Its documentation describes it as a marker for types that "act like" they own a `T`, and the Rustonomicon says it "consumes no space, but simulates a field of the given type for the purpose of static analysis". Concretely: - `size_of::<PhantomData<T>>()` is 0 and `align_of` is 1 for every `T` - both are guaranteed in the documentation; - **variance** of the struct follows the type you put inside, exactly as if a field of that type existed; - **auto traits** such as `Send` and `Sync` follow that type as well; - you construct it with the value `PhantomData`, no arguments; - it implements `Copy`, `Clone`, `Default`, `PartialEq`, `Eq`, `Ord` and `Hash` for every `T`, so `#[derive(Clone, Copy)]` on `Handle<'arena>` needs nothing extra. ## Choosing the marker | marker | variance in `'a` | `Send` / `Sync` of the marker | |---|---|---| | `PhantomData<&'a Arena>` or `PhantomData<&'a ()>` | covariant | both, if the referent is `Sync` | | `PhantomData<&'a mut ()>` | covariant in `'a` | both | | `PhantomData<Cell<&'a ()>>` | invariant | `Send`, not `Sync` | | `PhantomData<fn(&'a ()) -> &'a ()>` | invariant | both | | `PhantomData<fn(&'a ())>` | contravariant | both | | `PhantomData<*const &'a ()>` | covariant | neither | Each row holds on rustc 1.99.1: converting `Handle<'static>` to `Handle<'s>` and back, and requiring `Send` and `Sync`, succeed or fail as the table says. The selection rule follows from what the handle *means*: 1. If the handle logically holds a shared borrow of the arena, write `PhantomData<&'arena Arena>` - covariant, so a handle can be passed where a shorter-lived one is expected, just as a `&Arena` can. 2. If the lifetime must never be shrunk or widened - for example a lifetime that acts as an identity for one particular arena - pick an invariant form; `fn(&'a ()) -> &'a ()` does this without affecting `Send` or `Sync`. 3. Avoid raw-pointer markers unless you mean their auto-trait effect: they quietly make the handle neither `Send` nor `Sync`. ## What the handle then enforces With `PhantomData<&'arena Arena>` and a method `fn handle(&self, index: u32) -> Handle<'_>`, every handle keeps the arena borrowed for as long as it is used. Calling `arena.insert("enemy")`, which takes `&mut self`, while a handle is still used later fails with E0502 (cannot borrow `arena` as mutable because it is also borrowed as immutable). The handle stays 4 bytes, the size of its `u32`, because the marker occupies nothing. ## A word on drop check `PhantomData<T>` with a *type* parameter also tells the compiler the struct acts as if it owns a `T`. The standard library's own documentation now says this matters for drop check only "in very rare circumstances" and that the interaction may change. Since RFC 1238, a type with a `Drop` impl is already assumed to use its parameters when dropped, so an extra `PhantomData<T>` changes nothing there; it still changes variance and auto traits. Where ownership is not meant, `PhantomData<fn() -> T>` keeps covariance in `T` while being `Send` and `Sync` regardless of `T`.
- Why not store a real `&'arena Arena` field instead of the marker?That compiles and gives the same covariance, but it costs a pointer in every handle - 8 bytes on a 64-bit target beside a 4-byte index - and the handle never dereferences it, since methods take the arena as `&self`. `PhantomData<&'arena Arena>` expresses the same borrow relationship at zero size.
- What else changes if the marker is `PhantomData<Cell<&'arena ()>>`?`'arena` becomes invariant, and the handle stops being `Sync`, because `Cell` is `!Sync`; rustc 1.99.1 reports E0277 ("cannot be shared between threads safely") when such a handle is required to be `Sync`. `PhantomData<fn(&'arena ()) -> &'arena ()>` gives the same invariance without touching `Send` or `Sync`.
- For a type parameter, how do `PhantomData<T>` and `PhantomData<fn() -> T>` differ?Both are covariant in `T`. `PhantomData<T>` says the struct acts as if it owns a `T`, so `Send` and `Sync` follow `T`, and it can matter for drop check. `PhantomData<fn() -> T>` claims no ownership and is `Send` and `Sync` whatever `T` is.
- PhantomData adds a hidden pointer-sized field to the struct
- Any PhantomData marker gives the same variance, so the choice is cosmetic
- PhantomData<*const T> is a harmless covariant marker with no other effect
- A struct may declare a lifetime it never uses; rustc just ignores it
- Every type needs PhantomData<T> to get correct drop check, even with a Drop impl