Lifetime bound on generic type

Hello,
Is a lifetime bound on generic type still useful with the latest compiler? I have noticed it specified on some structs in std lib (like enum Cow).
In an older version of the Rust book, there was a section on Advanced lifetimes (Advanced Lifetimes - The Rust Programming Language) where an example is given as struct Ref<'a, T>(&'a T); which would not compile (T does not live long enough) and the solution is to introduce lifetime bound T: 'a . On the latest version of the compiler, I could however compile without the lifetime bound.
Also, this section is not present in the latest Rust book. Is this concept, not relevant anymore?

Is there an example, where the compiler would not be able to resolve lifetime of T without the lifetime bound explicitly specificied?

Thank you!

It's usually inferred from the field types now,[1] but it's still useful in at least three situations.

  1. It can't be inferred from the field types (probably you're using unsafe somewhere)

  2. You wanted a 'static bound -- 'static bounds are not inferred because the team thought it would be better to have that called out specifically. (Personally I find the inconsistency more confusing but :person_shrugging:.)

  3. If the generic may not be Sized -- T: ?Sized -- then there's still a difference between inferred bounds and explicit bounds when T = dyn Trait + '_.

Due to the last bullet point, if your generics can be ?Sized, it can be a breaking change to go between inferred and explicit.

Edit: Breakage examples.


  1. Here's the RFC â†Šī¸Ž

1 Like