The item's lifetime of global HashMap by lazy_static in Rust

525 Views Asked by At

I am new to Rust.

I define a global HashMap of User by lazy_static.

There is a lifetime in User, so I have to set a lifetime in lazy_static. It seems that only 'static can be used in lazy_static.

Here is the question: can I insert "non-static" User into the HashMap now?

Here is the code, which inserts a non-static User:

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

Here is the error:

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

1

There are 1 best solutions below

0
On

If you have to have a list of Users in each Class, and each User has a unique id, just store the ids in each instance of Class (and wherever else you would've had a reference to a User). u64 is Clone, so it all works.