Asynchronous 我如何在HashMap上等待rust中的未来值?
我试图在rust中启动一些异步任务,然后在代码中等待它们。以下是我的代码的简化版本:Asynchronous 我如何在HashMap上等待rust中的未来值?,asynchronous,rust,Asynchronous,Rust,我试图在rust中启动一些异步任务,然后在代码中等待它们。以下是我的代码的简化版本: 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
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);
}
但当我试着运行它时,我得到了一个自相矛盾的信息:
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`
我怎样才能等待我放入HashMap的未来?或者还有其他方法吗?使用
wait
要求未来
是固定和可变的
使用std::collections::HashMap;
异步fn my_async_fn()->i64{
返回0;
}
#[tokio::main]
异步fn main(){
让mut futures=HashMap::new();
insert(“a”,Box::pin(my_async_fn());
//这是我做其他工作的地方,不受这些未来的阻碍
让res_a=futures.get_mut(“a”).期待(“不可到达”).等待;
println!(“我的结果:{}”,res_a);
}
这是否回答了您的问题?等待未来需要可变的引用,而不是不变的引用。还要注意的是,在将未来插入HashMap
之前,您几乎肯定会希望将其框起来。如前所述,您的HashMap
将只接受通过调用my\u async\u fn()
生成的未来,这可能不是您想要的。@E\u net4saysdon'tcopythe-它没有完全回答我的问题,但是给了我一个更复杂的错误消息,Unpin
没有为来自\u generator::GenFuture…的实现。
我说过拥有可变引用是一个要求,而不是一个充分条件。链接问题中提到了Unpin
约束。