"borrowed value does not live long enough" when using tokio::spawn with a future with a mutable reference

Viewed 1509

The following code does not compile bceause the compiler can not assure hashmap_of_lists would live long enough. I can not overcome this.

I've tried using Arc and Mutex but then I had other issues because of the async fashion of some_func and using Mutex inside.

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

I get this error

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

0 Answers
Related