rust - Global mutable HashMap in a library -


this question has answer here:

i want have extendable dictionary linking object &'static str inside library. hashmap seems right data structure this, how make global, initialised on declaration , mutable?

so this:

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 { ... } 

this possible lazy_static crate. seen in example. since mutablity accessing static variable unsafe, need wrapped mutex. recommend not making hashmap public, instead provide set of methods lock, , provide access hashmap. see answer on making globally mutable singleton.

#[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 hashmap = hashmap.lock().unwrap();      hashmap.insert(3, "sample"); } 

Comments

Popular posts from this blog

get url and add instance to a model with prefilled foreign key :django admin -

android - Keyboard hides my half of edit-text and button below it even in scroll view -

css - Make div keyboard-scrollable in jQuery Mobile? -