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>
{
Box::new(a(r))
}
fn main() {
}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0310]: the parameter type `R` may not live long enough
--> src/lib.rs:14:5
|
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))
| ^^^^^^^^^^^^^^ ...so 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.