async fn main(){
let mut map:HashMap<String, Sender<i32>> = HashMap::new();
async fn send_msg(map: &mut HashMap<String, Sender<i32>>){
let (s, r) = bounded::<i32>(1);
map.insert(String::from("id"), s);
r.recv().await;
}
task::spawn(send_msg(&mut map)); // compiler already complains here
somefn(map) // need to use map afterwards too
println!("{}", "Ok()");
}
error[E0597]: `map` does not live long enough
--> src\main.rs:38:23
|
38 | task::spawn(send_msg(&mut map));
| ------^^^^^^^^-
| | |
| | borrowed value does not live long enough
| argument requires that `map` is borrowed for `'static`
...
55 | }
| - `map` dropped here while still borrowed
The prerequisite for spawning a task is that it doesn't borrow anything. This is so that it cannot be made invalid (holding references to deallocated memory) by the function that spawned it exiting (or being cancelled, if it's an async fn).
You will need to design so that anything the task need is owned, or shared with Arc, not borrowed. Maybe you could use a channel to send s to the owner of the map?