【发布时间】:2021-10-27 22:06:18
【问题描述】:
我是 Rust 的新手。
我通过lazy_static定义了一个User的全局HashMap。
User 中有生命周期,所以我必须在 lazy_static 中设置生命周期。看来lazy_static中只能使用'static。
问题来了:我现在可以在 HashMap 中插入“非静态”用户吗?
这是插入非静态用户的代码:
use std::collections::HashMap;
use lazy_static::lazy_static;
use std::sync::Mutex;
struct User<'a> {
name: &'a str,
score: f32,
}
lazy_static! {
static ref USERS: Mutex<HashMap<u64, User<'static>>> = Mutex::new(HashMap::new());
}
fn new_user(id: u64, name: &str, score: f32) {
let user = User { name, score };
USERS.lock().unwrap().insert(id, user);
}
fn remove_user(id: u64) {
USERS.lock().unwrap().remove(&id);
}
fn main() {
new_user(1, "hello", 1.2);
remove_user(1);
}
这是错误:
error[E0621]: explicit lifetime required in the type of `name`
--> src/main.rs:16:38
|
16 | USERS.lock().unwrap().insert(id, user);
| ^^^^ lifetime `'static` required
【问题讨论】:
-
你不能 - 因为
lazy_static使对象保持活动状态直到程序结束,接受除'static之外的任何生命周期都将允许在存储的值内进行引用(例如name在User类型的情况下)仍然在哈希映射中时变为无效。User结构应该拥有一个拥有的String而不是&str。 -
谢谢。我可以把名字改成
String,但是User里面会有其他的引用,比如&Class。它不能容纳一切。 -
我应该用
Arc<Class>代替&Class吗? -
那个,或者只是
Class,取决于用例。 -
我怀疑在您的情况下使用惰性静态是否有意义。 xy 问题我们在这里
标签: rust static lifetime lazy-static