What's the meaning of E0310

the following code can't compile

fn main() {
  struct U<'a,T>(&'a u8,T) where &T:'a;

the error is

error[E0310]: the parameter type `T` may not live long enough

I can understand that a lifetime outlive another lifetime, how a type outlive a lifetime?

You are specifying that a reference to T has lifetime 'a, but T could have a shorter lifetime. This works:

fn main() {
  struct U<'a,T>(&'a u8,T) where T:'a;

Sometimes it helps to think of lifetime bounds as validity bounds. Ty: 'lt means that type Ty is valid for at least everywhere that lifetime 'lt indicates. String: 'static not because any given String will live forever, but because any given String could live forever -- it is valid everywhere.

In practice it usually means "the type contains no references more constrained than the lifetime".

See also.

struct U<'a, T>(&'a u8, T) where &T: 'a;

The first error is that you elided a lifetime where elision isn't allowed, so let's fix that first:

struct U<'a, T>(&'a u8, T) where &'a T: 'a;

This compiles. The first error was throwing off the compiler and the second suggestion was unnecessary. It is true that T: 'a must hold for &'a T to be valid, but the compiler is aware of this very common construction and takes it as an implied bound. Something similar is true for &'a T: 'a, so you can leave that off too:

struct U<'a, T>(&'a u8, T);

Thank you for the elaborated explanation . I'm not completely understood . But I known not all legal syntax make practical sense . I'm just trying to explore all the possibilities of the grammar and see what will happen.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.