5

以下代码无法编译,因为编译器无法保证hashmap_of_lists会存在足够长的时间。我无法克服这一点。

我尝试过使用ArcMutex但是由于内部的异步方式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;
}

我收到这个错误

error[E0597]: `hashmap_of_lists` does not live long enough
  --> src/main.rs:12:23
   |
12 |     for (_, value) in hashmap_of_lists.iter_mut() {
   |                       ^^^^^^^^^^^^^^^^-----------
   |                       |
   |                       borrowed value does not live long enough
   |                       argument requires that `hashmap_of_lists` is borrowed for `'static`
...
19 | }
   | - `hashmap_of_lists` dropped here while still borrowed

4

0 回答 0