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