小编Gal*_*vid的帖子

当使用 tokio::spawn 和带有可变引用的 future 时,“借用的值存在的时间不够长”

以下代码无法编译,因为编译器无法保证hashmap_of_lists其寿命足够长。我无法克服这一点。

我尝试过使用ArcandMutex但由于内部some_func使用的异步方式,我遇到了其他问题Mutex

use futures; // 0.3.5
use std::collections::HashMap;
use tokio; // 0.2.21

async fn some_func(_some_slice: &mut [String]) {}

#[tokio::main]
async fn main() {
    let mut hashmap_of_lists = HashMap::<String, Vec<String>>::new();
    let mut join_handles = Vec::new();

    for (_, value) in hashmap_of_lists.iter_mut() {
        let future = some_func(value);
        let join_handle = tokio::task::spawn(future);
        join_handles.push(join_handle);
    }

    futures::future::join_all(join_handles).await;
}
Run Code Online (Sandbox Code Playgroud)

我收到这个错误

error[E0597]: `hashmap_of_lists` does not live long enough
  --> src/main.rs:12:23
   |
12 |     for (_, value) in hashmap_of_lists.iter_mut() …
Run Code Online (Sandbox Code Playgroud)

asynchronous reference rust rust-tokio borrow

5
推荐指数
0
解决办法
2070
查看次数

标签 统计

asynchronous ×1

borrow ×1

reference ×1

rust ×1

rust-tokio ×1