use lazy_static::lazy_static;
use std::collections::HashMap;
lazy_static! {
staticref HASHMAP: HashMap<u32, &'staticstr> = {
letmut m = HashMap::new();
m.insert(0, "foo");
m.insert(1, "bar");
m.insert(2, "baz");
m
};
}
fnmain() {
// 首次访问`HASHMAP`的同时对其进行初始化println!("The entry for `0` is \"{}\".", HASHMAP.get(&0).unwrap());
// 后续的访问仅仅获取值,再不会进行任何初始化操作println!("The entry for `1` is \"{}\".", HASHMAP.get(&1).unwrap());
}
rust
OnceLock
现在可以直接使用标准库中的 OnceLock 来实现 lazy_static 库的功能:
use std::collections::HashMap;
use std::sync::OnceLock;
fnhashmap() -> &'static HashMap<u32, &'staticstr> {
static HASHMAP: OnceLock<HashMap<u32, &str>> = OnceLock::new();
HASHMAP.get_or_init(|| {
letmut m = HashMap::new();
m.insert(0, "foo");
m.insert(1, "bar");
m.insert(2, "baz");
m
})
}
fnmain() {
// First access to `HASHMAP` initializes itprintln!("The entry for `0` is \"{}\".", hashmap().get(&0).unwrap());
// Any further access to `HASHMAP` just returns the computed valueprintln!("The entry for `1` is \"{}\".", hashmap().get(&1).unwrap());
}
error[E0716]: temporary value dropped while borrowed
--> src/main.rs:10:28
|
10 | CONFIG = Some(&mut Config {
| _________-__________________^
| |_________|
| ||
11 | || a: "A".to_string(),
12 | || b: "B".to_string(),
13 | || });
| || ^-- temporary value is freed at the end of this statement
| ||_________||
| |_________|assignment requires that borrow lasts for `'static`
| creates a temporary which is freed while still in use