gpt4 book ai didi

线程的 Rust 生命周期问题

转载 作者:行者123 更新时间:2023-11-29 08:32:09 25 4
gpt4 key购买 nike

代码如下:

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

我无法编译:

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

它提供的提示(添加一个&'static)没有帮助。

问题 1:如何使这段代码工作?

问题2:问题1解决后,想用std::sync::Arcmap线程安全,请问Rust 的方法?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com