Why does the Rust compiler emit an error requesting me to constrain the lifetime of the generic parameter in the following structure?
pub struct NewType<'a, T> {
x: &'a T,
}
error[E0309]: the parameter type `T` may not live long enough
--> src/main.rs:2:5
|
2 | x: &'a T,
| ^^^^^^^^
|
= help: consider adding an explicit lifetime bound `T: 'a`...
note: ...so that the reference type `&'a T` does not outlive the data it points at
--> src/main.rs:2:5
|
2 | x: &'a T,
| ^^^^^^^^
I can fix it by changing to
pub struct NewType<'a, T>
where
T: 'a,
{
x: &'a T,
}
I don't understand why it is necessary to add the T: 'a
part to the structure definition. I cannot think of a way that the data contained in T
could outlive the reference to T
. The referent of x
needs to outlive the NewType
struct and if T
is another structure then it would need to meet the same criteria for any references it contains as well.
Is there a specific example where this type of annotation would be necessary or is the Rust compiler just being pedantic?