summaryrefslogtreecommitdiffstats
path: root/third_party/rust/once_cell/examples/lazy_static.rs
blob: 3cdb19f2a5d34f5de6155e01c890d4cc94d65937 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
extern crate once_cell;

use once_cell::sync::{Lazy, OnceCell};
use std::collections::HashMap;

static HASHMAP: Lazy<HashMap<u32, &'static str>> = Lazy::new(|| {
    let mut m = HashMap::new();
    m.insert(0, "foo");
    m.insert(1, "bar");
    m.insert(2, "baz");
    m
});

// Same, but completely without macros
fn hashmap() -> &'static HashMap<u32, &'static str> {
    static INSTANCE: OnceCell<HashMap<u32, &'static str>> = OnceCell::new();
    INSTANCE.get_or_init(|| {
        let mut m = HashMap::new();
        m.insert(0, "foo");
        m.insert(1, "bar");
        m.insert(2, "baz");
        m
    })
}

fn main() {
    // First access to `HASHMAP` initializes it
    println!("The entry for `0` is \"{}\".", HASHMAP.get(&0).unwrap());

    // Any further access to `HASHMAP` just returns the computed value
    println!("The entry for `1` is \"{}\".", HASHMAP.get(&1).unwrap());

    // The same works for function-style:
    assert_eq!(hashmap().get(&0), Some(&"foo"));
    assert_eq!(hashmap().get(&1), Some(&"bar"));
}