我一直在try 使用以下函数来初始化值(这里是hashBrown的hashmap):
use std::collections::HashMap;
use std::sync::{Arc, Mutex};
use std::thread;
#[derive(Clone)]
struct Entity;
fn create_value(center: (f32, f32), length: f32) -> HashMap<(i32, i32), Option<Entity>> {
let cities: Arc<Mutex<HashMap<(i32, i32), Option<Entity>>>> = Arc::default();
let mut handles = vec![];
for i in 0..5 {
for j in 0..5 {
let city_thread = Arc::clone(&cities);
handles.push(thread::spawn(move || {
// do stuff in parallel
if let Ok(mut cities) = city_thread.lock() {
cities.insert((i, j), None);
}
}));
}
}
for handle in handles {
handle.join().unwrap();
}
// this part is the problem
if let Ok(city) = cities.lock() {
let city = city.clone();
return city;
} else {
panic!()
}
}
我得到以下错误:
`cities` does not live long enough
the temporary is part of an expression at the end of a block;
consider forcing this temporary to be dropped sooner, before the block's local variables are dropped
我知道我做错了什么,但我找不到任何东西或方法来返回值.