Returning impl Trait with static lifetime?

I have a function that returns an "impl Trait". The function accepts some parameters with lifetimes, but the output does not depend on the lifetimes. How can I convince the compiler of this fact? I would have thought that adding + 'static to the return type would work, but it does not work in the example below.

Edit: In the code below, I guess the compiler probably creates a new type for "impl B" that has R as a type parameter. Then the compiler cannot be convinced that "impl B" lives longer than R. So maybe nothing can be done in this case?

struct A {}

trait B {}

impl B for A {}

fn a<R>(_: &mut R) -> impl B + 'static
    A {}

fn b<R>(r: &mut R) -> Box<dyn B>

fn main() {



   Compiling playground v0.0.1 (/playground)
error[E0310]: the parameter type `R` may not live long enough
  --> src/
12 | fn b<R>(r: &mut R) -> Box<dyn B> //Box<dyn Fn() -> u8>
   |      - help: consider adding an explicit lifetime bound...: `R: 'static`
13 | {
14 |     Box::new(a(r))
   |     ^^^^^^^^^^^^^^ that the type `impl B` will meet its required lifetime bounds

error: aborting due to previous error

For more information about this error, try `rustc --explain E0310`.
error: could not compile `playground`.

To learn more, run the command again with --verbose.

1 Like

This is issue #42940. There is a workaround but it requires the unstable type_alias_impl_trait feature.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.