Arc<T> requiring a lifetime for T. Why?

Whenever you write Arc<dyn Trait + 'a>, then this has the following meaning:

This Arc can contain any value that implements the Trait trait, and has no lifetime annotations shorter than 'a.

When you create the Arc<dyn Trait>, then this is short-hand for Arc<dyn Trait + 'static>, so the compiler must ensure that the actual type has no lifetime annotations shorter than 'static.

However, generics are different than dyn Trait (impl Trait is short-hand for generics). When you use generics, they come with no restrictions on lifetimes annotated on the value, so an impl Test could be any type that implements Test, including types with very short lifetime annotations on them. By adding + 'static, you are saying "and this type must not have lifetime annotations shorter than 'static".

4 Likes