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
If you have to have a list of
User
s in eachClass
, and eachUser
has a uniqueid
, just store theid
s in each instance ofClass
(and wherever else you would've had a reference to aUser
).u64
isClone
, so it all works.