【问题标题】:The item's lifetime of global HashMap by lazy_static in RustRust 中lazy_static 的全局 HashMap 项目的生命周期
【发布时间】: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 之外的任何生命周期都将允许在存储的值内进行引用(例如nameUser 类型的情况下)仍然在哈希映射中时变为无效。 User 结构应该拥有一个拥有的 String 而不是 &amp;str
  • 谢谢。我可以把名字改成String,但是User里面会有其他的引用,比如&amp;Class。它不能容纳一切。
  • 我应该用Arc&lt;Class&gt;代替&amp;Class吗?
  • 那个,或者只是Class,取决于用例。
  • 我怀疑在您的情况下使用惰性静态是否有意义。 xy 问题我们在这里

标签: rust static lifetime lazy-static


【解决方案1】:

如果您必须在每个Class 中拥有一个Users 列表,并且每个User 都有一个唯一的id,则只需将ids 存储在Class 的每个实例中(以及任何位置否则你会参考User)。 u64Clone,所以一切正常。

【讨论】:

    猜你喜欢
    • 2013-07-03
    • 2020-12-31
    • 1970-01-01
    • 2015-09-24
    • 1970-01-01
    • 1970-01-01
    • 2017-05-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多