Here is the code:
use std::collections::HashMap;
use std::thread;
type MAP = HashMap<String, String>;
fn handle_n_times(count: i32, map: &mut MAP) {
for i in 0..count {
thread::spawn(move || {
map.insert(format!("key-{}", i), format!("value-{}", i));
});
}
}
fn main() {
let mut map: MAP = MAP::new();
handle_n_times(5, &mut map);
}
I cannot compile:
error[E0621]: explicit lifetime required in the type of `map`
--> src/main.rs:8:9
|
6 | fn handle_n_times(count: i32, map: &mut MAP) {
| -------- help: add explicit lifetime `'static` to the type of `map`: `&'static mut std::collections::HashMap<std::string::String, std::string::String>`
7 | for i in 0..count {
8 | thread::spawn(move || {
| ^^^^^^^^^^^^^ lifetime `'static` required
The hint it provides (add a &'static
) is not helpful.
Question 1: How to make this code work?
Question 2: After 1 solved, I want to use std::sync::Arc
to make map
thread-safe, what's the Rust way to do it?