lotsoftools

Understanding Rust Error E0772

Introduction

Rust Error E0772 occurs when a trait object has a specific lifetime '1, but it is used in a way that requires it to have a 'static lifetime. This error occurs because the compiler infers an incorrect 'static lifetime for an omitted lifetime in the trait object.

Erroneous Code Example

#![allow(unused)]
fn main() {
trait BooleanLike {}
trait Person {}

impl BooleanLike for bool {}

impl dyn Person {
    fn is_cool(&self) -> bool {
        // hey you, you're pretty cool
        true
    }
}

fn get_is_cool<'p>(person: &'p dyn Person) -> impl BooleanLike {
    // error: `person` has an anonymous lifetime `'p` but calling
    //        `print_cool_fn` introduces an implicit `'static` lifetime
    //        requirement
    person.is_cool()
}
}

Explanation

In the erroneous code example above, the trait object 'person' in function 'get_is_cool' has its own implicit lifetime '2. This lifetime represents the data the trait object might hold inside. Lifetime '2 must outlive any lifetime a struct made into a trait object may have.

However, since the '2 lifetime is omitted in the implementation for 'dyn Person', the compiler infers it as 'static. This introduces a conflict between lifetimes, which is the core of the problem.

Solution

To fix Rust Error E0772, you can simply be generic over the '2 lifetime, preventing the compiler from inferring it as 'static. This can be done as shown below:

#![allow(unused)]
fn main() {
trait Person {}

impl<'d> dyn Person + 'd {/* ... */}

// This works too, and is more elegant:
//impl dyn Person + '_ {/* ... */}
}

Conclusion

Rust Error E0772 can be resolved by correctly specifying the lifetime '2 while implementing the trait object. This ensures that there is no conflict between lifetimes and the code compiles as expected. To further improve your understanding of trait object lifetimes, refer to the Rust Reference on Trait Object Lifetime Bounds.