简体   繁体   中英

How can I await on HashMap future values in rust?

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?

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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM