1 #### Note: this error code is no longer emitted by the compiler.
3 A trait object has some specific lifetime `'1`, but it was used in a way that
4 requires it to have a `'static` lifetime.
6 Example of erroneous code:
12 impl BooleanLike for bool {}
15 fn is_cool(&self) -> bool {
16 // hey you, you're pretty cool
21 fn get_is_cool<'p>(person: &'p dyn Person) -> impl BooleanLike {
22 // error: `person` has an anonymous lifetime `'p` but calling
23 // `print_cool_fn` introduces an implicit `'static` lifetime
29 The trait object `person` in the function `get_is_cool`, while already being
30 behind a reference with lifetime `'p`, also has it's own implicit lifetime,
33 Lifetime `'2` represents the data the trait object might hold inside, for
39 struct MyStruct<'a>(&'a i32);
41 impl<'a> MyTrait for MyStruct<'a> {}
44 With this scenario, if a trait object of `dyn MyTrait + '2` was made from
45 `MyStruct<'a>`, `'a` must live as long, if not longer than `'2`. This allows the
46 trait object's internal data to be accessed safely from any trait methods. This
47 rule also goes for any lifetime any struct made into a trait object may have.
49 In the implementation for `dyn Person`, the `'2` lifetime representing the
50 internal data was omitted, meaning that the compiler inferred the lifetime
51 `'static`. As a result, the implementation's `is_cool` is inferred by the
52 compiler to look like this:
58 fn is_cool<'a>(self: &'a (dyn Person + 'static)) -> bool {unimplemented!()}
62 While the `get_is_cool` function is inferred to look like this:
66 # trait BooleanLike {}
68 fn get_is_cool<'p, R: BooleanLike>(person: &'p (dyn Person + 'p)) -> R {
73 Which brings us to the core of the problem; the assignment of type
74 `&'_ (dyn Person + '_)` to type `&'_ (dyn Person + 'static)` is impossible.
76 Fixing it is as simple as being generic over lifetime `'2`, as to prevent the
77 compiler from inferring it as `'static`:
82 impl<'d> dyn Person + 'd {/* ... */}
84 // This works too, and is more elegant:
85 //impl dyn Person + '_ {/* ... */}
88 See the [Rust Reference on Trait Object Lifetime Bounds][trait-objects] for
89 more information on trait object lifetimes.
91 [trait-object-lifetime-bounds]: https://doc.rust-lang.org/reference/types/trait-object.html#trait-object-lifetime-bounds