From my own understanding and experimentation this appears to be true, but I have yet to find an authoritative source that documents it. Rust by Example has a bounds section where it says:
T: 'a
: All references inT
must outlive lifetime'a
.#[derive(Debug)] struct Ref<'a, T: 'a>(&'a T); // `Ref` contains a reference to a generic type `T` that has // an unknown lifetime `'a`. `T` is bounded such that any // *references* in `T` must outlive `'a`. Additionally, the lifetime // of `Ref` may not exceed `'a`.
However, this looks like a poor demonstration since the T: 'a
bound does not seem to affect the behavior of Ref
. Any attempt I've made to construct a T
that is shorter than 'a
is thwarted with or without T: 'a
. Even more, a generic reference defined without the lifetime bound can be passed off as one with it:
fn f<'a, T>(r: &'a T) {
g(r) // this compiles
}
fn g<'a, T: 'a>(r: &'a T) {
// ...
}
The Rust Reference has a similar construction from some examples in the generic parameters section (struct Ref<'a, T> where T: 'a { r: &'a T }
), however it does not elaborate. I have looked through the documentation there, those on references, and on lifetimes and cannot find a link.
So does &'a T
imply T: 'a
? If so, where is this documented? And why do these resources have this unnecessary constraint? If not, what are the rules?
T
) which does not compile ifT: 'a
constraint isn't used in Ref type you quoted. – UnavailingT
because theT: 'a
bound exists regardless due to the usage of&'a T
. So there is no difference with or without writing it explicitly. – Dutiful