Any idea how can I achieve something like the following?
The compiler complains that tx
doesn't live long enough, and rightly so. How can I return a future that captures the variables it needs?
use std::future::Future;
async fn register_callback<F>(f :impl Fn() -> F)
where
F: Future + Send + 'static
{
f().await;
}
#[tokio::main]
async fn main() {
let (tx, _) = tokio::sync::mpsc::channel::<()>(1);
register_callback(|| {
tx.clone().send(())
});
}
https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=efc41e0f468fb770fe1e26c15f8335ba
I think I did it. Thanks!
use std::future::Future;
async fn register_callback<F>(f :impl Fn() -> F)
where
F: Future + Send + 'static
{
f().await;
}
#[tokio::main]
async fn main() {
let (tx, _) = tokio::sync::mpsc::channel::<()>(1);
register_callback(|| {
let x = tx.clone();
async move {x.send(()).await.unwrap();}
}).await;
}
1 Like
system
Closed
3
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.