库中的全局可变 HashMap
Global mutable HashMap in a library
我想要一个可扩展的字典,将 Object
与我的图书馆中的 &'static str
链接在一起。 HashMap
似乎是正确的数据结构,但我如何使它成为全局的、在声明时初始化和可变的?
所以像这样:
use std::collections::HashMap;
enum Object { A, B, C }
const OBJECT_STR: &'static [&'static str] = &[ "a", "b", "c" ];
static mut word_map: HashMap<&'static str, Object> = {
let mut m = HashMap::new();
m.insert(OBJECT_STR[0], Object::A);
m.insert(OBJECT_STR[1], Object::B);
m.insert(OBJECT_STR[2], Object::C);
m
};
impl Object {
...
}
这可以通过 lazy_static
crate. As seen in their example. Since mutablity accessing a static variable is unsafe, it would need to wrapped into a Mutex
. I would recommend not making the HashMap
public, but instead provide a set of methods that lock, and provide access to the HashMap
. See this answer 创建一个全局可变的单例来实现。
#[macro_use]
extern crate lazy_static;
use std::collections::HashMap;
use std::sync::Mutex;
lazy_static! {
static ref HASHMAP: Mutex<HashMap<u32, &'static str>> = {
let mut m = HashMap::new();
m.insert(0, "foo");
m.insert(1, "bar");
m.insert(2, "baz");
Mutex::new(m)
};
}
fn main() {
let mut map = HASHMAP.lock().unwrap();
map.insert(3, "sample");
}
我想要一个可扩展的字典,将 Object
与我的图书馆中的 &'static str
链接在一起。 HashMap
似乎是正确的数据结构,但我如何使它成为全局的、在声明时初始化和可变的?
所以像这样:
use std::collections::HashMap;
enum Object { A, B, C }
const OBJECT_STR: &'static [&'static str] = &[ "a", "b", "c" ];
static mut word_map: HashMap<&'static str, Object> = {
let mut m = HashMap::new();
m.insert(OBJECT_STR[0], Object::A);
m.insert(OBJECT_STR[1], Object::B);
m.insert(OBJECT_STR[2], Object::C);
m
};
impl Object {
...
}
这可以通过 lazy_static
crate. As seen in their example. Since mutablity accessing a static variable is unsafe, it would need to wrapped into a Mutex
. I would recommend not making the HashMap
public, but instead provide a set of methods that lock, and provide access to the HashMap
. See this answer 创建一个全局可变的单例来实现。
#[macro_use]
extern crate lazy_static;
use std::collections::HashMap;
use std::sync::Mutex;
lazy_static! {
static ref HASHMAP: Mutex<HashMap<u32, &'static str>> = {
let mut m = HashMap::new();
m.insert(0, "foo");
m.insert(1, "bar");
m.insert(2, "baz");
Mutex::new(m)
};
}
fn main() {
let mut map = HASHMAP.lock().unwrap();
map.insert(3, "sample");
}