When should I use `T: 'a` in a type/trait definition?

What is the difference in practice between

struct Ref<'a, T: 'a>(&'a T);

and

struct Ref<'a, T>(&'a T);

The second is shorter and more general. When can the first option come in handy?

These two things must be equivalent, AFAIK, since the mere existence (and well-formedness) of &'a T implies T: 'a.

2 Likes

I found an example of the first option:

pub struct Ref<'b, T: ?Sized + 'b> {
    value: &'b T,
    borrow: BorrowRef<'b>,
}

What is T: .. + 'b here for? Just to be clear and explicit?

I thought the + 'a was required to be written on structs and enums specifically. If this is no longer the case then that's nice...

(aaaaaand family just arrived so I guess any actual testing will have to wait...)

1 Like

There is no difference.

Rust Edition 2018 has explicitly allowed the second syntax as an abbreviation for the first one. That's because it's logically not possible to take a reference to T that doesn't live as long or longer than the reference itself, so &'a T can't exist without T: 'a (T outlives loan marked by 'a) being true.

7 Likes

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.