Is there a workaround for creating an async closure that holds a reference over an await point?
Example:
use std::time::Duration;
use tokio::time::sleep;
fn main() {
let closure = |v: &u64| async move {
sleep(Duration::from_secs(1)).await;
println!("{}", v);
};
}
Fails with:
error: lifetime may not live long enough
--> src/main.rs:5:29
|
5 | let closure = |v: &u64| async move {
| _______________________-___-_^
| | | |
| | | return type of closure `[async block@src/main.rs:5:29: 8:6]` contains a lifetime `'2`
| | let's call the lifetime of this reference `'1`
6 | | sleep(Duration::from_secs(1)).await;
7 | | println!("{}", v);
8 | | };
| |_____^ returning this value requires that `'1` must outlive `'2`
I'm aware that async closures could help. This works:
#![feature(async_closure)]
use std::time::Duration;
use tokio::time::sleep;
fn main() {
let closure = async move |v: &u64| {
sleep(Duration::from_secs(1)).await;
println!("{}", v);
};
}
but given that they're not stable yet, I was wondering if there is any other workaround to make this work.