use std::future::Future;
pub trait AsyncFnOnce<Arg>: FnOnce(Arg) -> <Self as AsyncFnOnce<Arg>>::Fut {
type Fut: Future<Output = <Self as AsyncFnOnce<Arg>>::Output>;
type Output;
}
impl<Arg, Func: FnOnce(Arg) -> Fut, Fut: Future> AsyncFnOnce<Arg> for Func {
type Fut = Fut;
type Output = Fut::Output;
}
// --------------------------------------------------------------
async fn baz(cb: impl for<'buf> AsyncFnOnce<&'buf mut Vec<u8>>) {
let mut buf = vec![];
cb(&mut buf).await;
println!("{buf:?}");
}
#[tokio::main]
async fn main() {
baz(|s: &mut Vec<u8>| async move {
s.push(1);
});
}
Error:
error: lifetime may not live long enough
--> src/main.rs:22:27
|
22 | baz(|s: &mut Vec<u8>| async move {
| _____________-___________-_^
| | | |
| | | return type of closure `[async block@src/main.rs:22:27: 24:6]` contains a lifetime `'2`
| | let's call the lifetime of this reference `'1`
23 | | s.push(1);
24 | | });
| |_____^ returning this value requires that `'1` must outlive `'2
How can I solve it ?
Edit: I still don't know why rust is complaining about. The error message is not very helpful.