Reputation: 1006
I'm trying to kick off some async tasks in rust, then await them later in the code. Here's a simplified version of my code:
async fn my_async_fn() -> i64 {
return 0;
}
async fn main() {
let mut futures = HashMap::new();
futures.insert("a", my_async_fn());
// this is where I would do other work not blocked by these futures
let res_a = futures.get("a").expect("unreachable").await;
println!("my result: {}", res_a);
}
But when I try to run this, I get this self-contradictory message:
error[E0277]: `&impl futures::Future` is not a future
--> my/code:a:b
|
111 | let res_a = futures.get("a").expect("unreachable").await;
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ `&impl futures::Future` is not a future
|
= help: the trait `futures::Future` is not implemented for `&impl futures::Future`
= note: required by `futures::Future::poll`
How can I await futures that I've put into a HashMap? Or is there another way altogether?
Upvotes: 1
Views: 1976
Reputation: 4775
Using await
requires the Future
is pinned and mutable.
use std::collections::HashMap;
async fn my_async_fn() -> i64 {
return 0;
}
#[tokio::main]
async fn main() {
let mut futures = HashMap::new();
futures.insert("a", Box::pin(my_async_fn()));
// this is where I would do other work not blocked by these futures
let res_a = futures.get_mut("a").expect("unreachable").await;
println!("my result: {}", res_a);
}
Upvotes: 2