confusion about PhantomData & T: 'a
Nobody has claimed this yet.
- Dominant language
- CSS
- Stars
- 2.3k
- Forks
- 325
- PR merge metrics
- No merged PRs in 30d
Description
My current understanding of PhantomData<T> is: You need it if your struct "contains/owns" a T, even though there is no field to reflect that fact.
But neither the nomicon nor the rust docs of PhantomData seem to confirm this:
If PhantomData truly indicated containment to the compiler, why does the Drain impl for the example vec use a lifetime bound for T?
pub struct Drain<'a, T: 'a> {
vec: PhantomData<&'a mut Vec<T>>, // this should imply `T: 'a`
iter: RawValIter<T>,
}
In the past, you needed T: 'a, but that has since been removed by rfc2093.
Instead, the presence of a &'a T field indicates that T: 'a.
So if PhantomData behaved like a field of the same type, the lifetime bound should not be necessary, because it is inferred transitively, all the way from RawVec.
The PhantomData docs explicitly state that T: 'a is required:
struct Slice<'a, T: 'a> {
start: *const T,
end: *const T,
phantom: PhantomData<&'a T>,
}
"This also in turn requires the annotation T: 'a, indicating that any references in T are valid over the lifetime 'a."
What makes it even more confusing is that there is a pretty consistent pattern: The nomicon, the rust docs, and the rust std source code use T: 'a when implementing reference-like types, but not for owning types like Vec.
Is T: 'a ever required if PhantomData is used?
I think it would be great if the nomicon could provide a definite answer to this question. And if PhantomData obsoletes T: 'a, it would be very useful to include some info about this being a thing of the past.
Contributor guide
No contributing guide indexed for this repository
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
Start by comparing the Nomicon Vec example, the Rust PhantomData documentation, and RFC 2093, focusing on how they describe T: 'a for owning and reference-like types. Determine the definitive rule and identify where the Nomicon should explain it. Done means the documentation resolves whether PhantomData makes the explicit bound necessary and updates the relevant explanation.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- rust
- Domain
- documentation
- Issue type
- Documentation
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100