Continuing the discussion from Can't express lifetime for closure arguments (needed for async):
I still would like to avoid the workaround (as discussed in the original thread). However, until there's a solution, I'm willing to use Pin<Box<dyn Future>>
.
The playground linked above does work. However, when things get a bit more complex, I run into problems:
I was able to reproduce the error:
use std::future::Future;
use std::pin::Pin;
trait Something {
fn something(&self) {}
}
struct Executor<I> {
inner: I,
}
async fn call_closure<C>(mut closure: C)
where
C: for<'a> FnMut(&'a str) -> Pin<Box<dyn 'a + Future<Output = ()>>>,
{
let s = String::from("Hello World!");
closure(&s).await;
}
impl<I> Executor<I>
where
I: Something,
{
pub async fn run(&self) {
call_closure(|s| {
Box::pin(async move {
self.inner.something();
println!("{s}");
})
})
.await;
}
}
Errors:
Compiling playground v0.0.1 (/playground)
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/lib.rs:24:22
|
24 | pub async fn run(&self) {
| ^^^^^
|
note: first, the lifetime cannot outlive the lifetime `'_` as defined here...
--> src/lib.rs:24:22
|
24 | pub async fn run(&self) {
| ^
note: ...so that the expression is assignable
--> src/lib.rs:24:22
|
24 | pub async fn run(&self) {
| ^^^^^
= note: expected `&Executor<I>`
found `&Executor<I>`
note: but, the lifetime must be valid for the anonymous lifetime #1 defined here...
--> src/lib.rs:25:22
|
25 | call_closure(|s| {
| ______________________^
26 | | Box::pin(async move {
27 | | self.inner.something();
28 | | println!("{s}");
29 | | })
30 | | })
| |_________^
note: ...so that the types are compatible
--> src/lib.rs:26:13
|
26 | / Box::pin(async move {
27 | | self.inner.something();
28 | | println!("{s}");
29 | | })
| |______________^
= note: expected `Pin<Box<dyn Future<Output = ()>>>`
found `Pin<Box<dyn Future<Output = ()>>>`
For more information about this error, try `rustc --explain E0495`.
error: could not compile `playground` due to previous error
I don't understand the error message:
error[E0495]: cannot infer an appropriate lifetime due to conflicting requirements
--> src/lib.rs:24:22
|
24 | pub async fn run(&self) {
| ^^^^^
|
note: first, the lifetime cannot outlive the lifetime `'_` as defined here...
--> src/lib.rs:24:22
|
24 | pub async fn run(&self) {
| ^
self
needs to outlive itself!?
= note: expected `&Executor<I>`
found `&Executor<I>`
Uhhhh!?
= note: expected `Pin<Box<dyn Future<Output = ()>>>`
found `Pin<Box<dyn Future<Output = ()>>>`
This doesn't make sense (to me). Any idea what's going on or wrong in my code?