lazy_static.rs 1.0 KB

123456789101112131415161718192021222324252627282930313233343536
  1. extern crate once_cell;
  2. use once_cell::sync::{Lazy, OnceCell};
  3. use std::collections::HashMap;
  4. static HASHMAP: Lazy<HashMap<u32, &'static str>> = Lazy::new(|| {
  5. let mut m = HashMap::new();
  6. m.insert(0, "foo");
  7. m.insert(1, "bar");
  8. m.insert(2, "baz");
  9. m
  10. });
  11. // Same, but completely without macros
  12. fn hashmap() -> &'static HashMap<u32, &'static str> {
  13. static INSTANCE: OnceCell<HashMap<u32, &'static str>> = OnceCell::new();
  14. INSTANCE.get_or_init(|| {
  15. let mut m = HashMap::new();
  16. m.insert(0, "foo");
  17. m.insert(1, "bar");
  18. m.insert(2, "baz");
  19. m
  20. })
  21. }
  22. fn main() {
  23. // First access to `HASHMAP` initializes it
  24. println!("The entry for `0` is \"{}\".", HASHMAP.get(&0).unwrap());
  25. // Any further access to `HASHMAP` just returns the computed value
  26. println!("The entry for `1` is \"{}\".", HASHMAP.get(&1).unwrap());
  27. // The same works for function-style:
  28. assert_eq!(hashmap().get(&0), Some(&"foo"));
  29. assert_eq!(hashmap().get(&0), Some(&"bar"));
  30. }