Struct lifetime bound

It is possible to write both:

struct S<'a, T: 'static> { b: &'a T }
struct S<'a, T: 'a> { b: &'a T }

So I presume that there are some contexts in which the first expression is allowed and the second one is forbidden, and conversely some contexts in which the first expression is forbidden and the second one is allowed.
Here is a context in which only the second expression is allowed:

// Forbidden
struct S<'a, T: 'static> { b: &'a T }
let n = 12;
let r = &n;
let s = S { b: &r };

// Allowed
struct S<'a, T: 'a> { b: &'a T }
let n = 12;
let r = &n;
let s = S { b: &r };

What is an example of a context in which only the first expression is allowed?

In type definition you probably won't need it explicitly, because 'a (or any other non-static name) allows any lifetime, including 'static as a special case. There are places where static lifetime is required, but in these cases Rust will automatically assume 'a == 'static or refuse to compile if that isn't true.

1 Like