Sub topic 1
Generic types and the unused parameter error
Rust lets you declare a type parameter on a struct and then not use it. The compiler rejects that, and the rejection explains why PhantomData exists. This chapter covers the rule, the reasons for it, and the first fix. Later chapters build marker types and typestate APIs on top of that fix.
Prerequisites
This chapter assumes you already know:
- Ownership, borrowing and move semantics.
- Structs, enums and
implblocks. - Generic type parameters and trait bounds.
- How to run
cargo buildand read a compiler error message.
You don't need any knowledge of PhantomData or of zero-sized types. Both are introduced in the next chapters.
Generic structs: a short refresher
A generic struct declares a type parameter in angle brackets and uses it in at least one field.
struct Wrapper<T> {
value: T,
}
impl<T> Wrapper<T> {
fn new(value: T) -> Self {
Wrapper { value }
}
fn into_inner(self) -> T {
self.value
}
}
fn main() {
let a = Wrapper::new(42u32);
let b = Wrapper::new(String::from("hello"));
println!("{} {}", a.into_inner(), b.into_inner());
}Wrapper<u32> and Wrapper<String> are two different types. The compiler generates separate code for each (monomorphization), and a value of one cannot be used where the other is expected. The parameter T changes the type's identity, and here it also changes the data the struct stores.
The idea behind phantom types is to keep the first effect and drop the second. You want Id<User> and Id<Order> to be different types even though both hold only a u64.
The unused parameter error
The obvious attempt at a typed ID is this:
struct Id<T> {
raw: u64,
}This does not compile. The compiler reports error E0392:
error[E0392]: type parameter `T` is never used
--> src/main.rs:1:11
|
1 | struct Id<T> {
| ^ unused type parameter
|
= help: consider removing `T`, referring to it in a field, or using a marker such as `PhantomData`The exact wording and line numbers vary between compiler versions. The error code and the three suggestions stay the same:
- Remove the parameter.
- Use it in a field.
- Use a marker such as
PhantomData.
The rule applies to every type definition that declares parameters: structs, enums and unions. An enum has to use each parameter in at least one variant:
// Does not compile: `R` is never used.
enum Either<L, R> {
Left(L),
}Adding a second variant Right(R) fixes it. Using the parameter in any field of any variant is enough.
Why the compiler insists
The rule can look pedantic. A parameter that is never used cannot cause a runtime problem, so why refuse it? The reason is that the compiler does not only check the layout of your data. It also derives properties of the type from how each parameter is used in the fields. Three of them matter here.
- Variance. For types like
Wrapper<&'a str>, the compiler must decide whether aWrapper<&'long str>can be used where aWrapper<&'short str>is expected. It answers this by looking at howTappears in the fields. With no field mentioningT, there is nothing to look at. Rust treats this as an error instead of silently picking an answer that might be unsound. - Drop check. When a value is dropped, the compiler must know whether it might own, and therefore drop, a
T. This decides whether data thatTborrows must still be alive at that point. - Auto traits.
SendandSyncare implemented automatically when all fields areSendorSync. IfTappears in no field, the compiler has no basis for deciding whether the struct is thread-safe with respect toT.
So an unused parameter leaves these properties undefined. The compiler asks you to say what the relationship to T is. PhantomData<T> is how you say it. Chapter 11 returns to variance, drop check and auto traits in detail. For now, keep the principle: a type parameter must be tied to a field so the compiler can reason about it.
The fix: PhantomData
std::marker::PhantomData<T> is a type from the standard library that takes no space at runtime. It has one value, also written PhantomData. Placing it in a field counts as "using" T, and the compiler treats the struct as if it logically contained a T.
use std::marker::PhantomData;
struct Id<T> {
raw: u64,
_marker: PhantomData<T>,
}
impl<T> Id<T> {
fn new(raw: u64) -> Self {
Id { raw, _marker: PhantomData }
}
}
struct User;
struct Order;
fn main() {
let user_id: Id<User> = Id::new(1);
let order_id: Id<Order> = Id::new(1);
println!("{} {}", user_id.raw, order_id.raw);
println!("size of Id<User>: {}", std::mem::size_of::<Id<User>>());
}This compiles and prints 1 1 and then size of Id<User>: 8. The struct is exactly the size of its u64. The marker field adds nothing.
Two details:
PhantomDataappears twice with different meanings. In the field typePhantomData<T>, it is a type. In the constructor_marker: PhantomData, it is the single value of that type. The compiler infersTfrom the field declaration.- The leading underscore in
_markersilences the dead-code warning about a field that is never read. The field is never meant to be read.
The next chapters cover why such a field costs no memory (zero-sized types) and how to use it as a tag. This chapter focuses on the error and the first fix.
When the parameter is a lifetime
E0392 also applies to lifetime parameters. A struct that declares 'a must use it:
// Does not compile: lifetime parameter `'a` is never used.
struct View<'a> {
ptr: *const u8,
len: usize,
}Raw pointers carry no lifetime, so this struct looks fine to a programmer but gives 'a nowhere to appear. The fix is the same:
use std::marker::PhantomData;
struct View<'a> {
ptr: *const u8,
len: usize,
_borrow: PhantomData<&'a [u8]>,
}
impl<'a> View<'a> {
fn new(data: &'a [u8]) -> Self {
View {
ptr: data.as_ptr(),
len: data.len(),
_borrow: PhantomData,
}
}
fn len(&self) -> usize {
self.len
}
}
fn main() {
let bytes = vec![1u8, 2, 3];
let view = View::new(&bytes);
println!("{} bytes, first pointer is null: {}", view.len(), view.ptr.is_null());
// drop(bytes); // error if uncommented: `bytes` is borrowed while `view` is still used
}PhantomData<&'a [u8]> tells the compiler that View behaves as if it held a shared borrow of a byte slice for 'a. As a result, bytes cannot be moved or dropped while view is alive, even though no real reference is stored. This is the main non-marker use of PhantomData: giving a lifetime to unsafe code that holds raw pointers.
Related cases that look similar
Three nearby situations are easy to confuse with E0392. They behave differently.
| Situation | Example | Result |
|---|---|---|
| Unused parameter on a type | `struct Id<T> { raw: u64 }` | Error E0392 |
| Unused parameter on a function | `fn make<T>() -> u32 { 0 }` | Compiles, but callers must name `T` |
| Unused parameter on an `impl` | `impl<T> Id { ... }` | Error E0207 (unconstrained parameter) |
A function with an unused type parameter is legal. The compiler cannot infer T from the arguments, so each call needs an explicit turbofish, such as make::<String>(). Some APIs use this deliberately to select behavior at the call site.
An impl block is stricter. Every parameter of impl<T> must appear in the implemented type, in the trait being implemented, or in an associated-type constraint. If it doesn't, the compiler cannot work out which T an impl refers to, and it reports E0207. This matters later: when you write impl<S> Door<S>, the S is constrained because Door<S> mentions it.
Choosing a fix
When you meet E0392, work through the options in order. The first option that fits is usually the right one.
The first question is not a formality. Many E0392 errors come from leftover parameters after a refactor, and removal is the correct fix. Use PhantomData when the parameter carries meaning for the type system but no data. Typed IDs, state tags and borrowed lifetimes on raw pointers are the standard cases.
Common mistakes
- Using the type in a method only. Mentioning
Tin a method signature, as infn get(&self) -> T, does not satisfy the rule. Only field types count. - Writing
PhantomDatawithout a type. A field declared as_marker: PhantomDatahas no parameter to fill in and fails with a missing generics error. Always writePhantomData<T>. - Using a plain
Tfield instead. Storing a realTin a field works, but then the struct owns aTand its size depends onT. That changes the layout and requires you to construct a value ofTfor every instance. - Forgetting the marker when constructing. Struct literals must initialize
_marker: PhantomData, because the field exists even though it holds nothing. A constructor likeId::newkeeps this detail in one place. - Assuming the choice of form is free.
PhantomData<T>,PhantomData<&'a T>andPhantomData<fn() -> T>all satisfy the compiler, but they give the struct different variance, drop-check andSend/Syncbehavior.PhantomData<T>is the default for "acts as if it owns aT". Chapter 11 explains how to choose.
Exercise
This code fails with E0392. Explain why, and give two different fixes, one of which keeps the parameter. struct Meters<Unit> { amount: f64, }
Show answer
The struct declares Unit but no field uses it, so the compiler cannot derive variance, drop-check or auto-trait behavior for that parameter. Fix 1: remove the parameter, giving struct Meters { amount: f64 }, which is right if Unit was never needed. Fix 2: keep it by adding a marker field, struct Meters<Unit> { amount: f64, _unit: std::marker::PhantomData<Unit> }, and initialize it with _unit: PhantomData in every struct literal. The second fix adds no memory, so size_of::<Meters<()>>() is still 8.
Exercise
Why does fn make<T>() -> u32 { 0 } compile while impl<T> Meters { } for a non-generic Meters does not? What does a caller of make have to do?
Show answer
A function may declare a type parameter that appears nowhere in its signature, because the parameter only selects an instantiation. The caller must name it explicitly, as in make::<String>(), since inference has nothing to work from. An impl block is different. Every parameter must be constrained by the implemented type, the trait, or an associated type, and here Meters does not mention T. The compiler cannot tell which T the block applies to and reports E0207.