Lifetime parameter in From Error impl for Boxed Error type objects


I stumbled over the From implementation to convert types implementing the Error trait to boxed trait objects:

impl<'a, E: Error + 'a> From<E> for Box<Error + 'a> {
    fn from(err: E) -> Box<Error + 'a> {

Now I am wondering: why do we need lifetime bounds here? What do these lifetime bounds even express? I am not sure why we need to specify a lifetime here at all, since the E is moved into a Box anyway.



fn err_msg<'a>(s: &'a str) -> Box<Error + 'a> {

Just because you don’t see a borrow doesn’t mean there aren’t lifetimes involved. Without those lifetimes, that From impl would be limited to Box<Error + 'static>, i.e. it would only work for types that are not lifetime-constrained in any way whatsoever.


It’s more general with the lifetime parameter than without it.

As written, it’s an implementation that creates a Box<Error + 'a> for any E that implements Error and outlives 'a.

The 'a is a generic parameter, so you just substitute in the case that applies for a particular type. For example, &'xyz str can make a Box<Error + 'xyz> trait object. And String can make a Box<Error + 'static> trait object, because String: 'static (it contains no references).