[pre-RFC] lazy-static move to std

WAIT WAT? We actually can provide a nice API with stable Rust! We have associated constants & conversion from lambdas to function pointers!

Playground

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

// macro and indirect fn call
static HASHMAP: Lazy<HashMap<u32, &'static str>> = lazy! {
    let mut m = HashMap::new();
    m.insert(0, "foo");
    m.insert(1, "bar");
    m.insert(2, "baz");
    m
};

// monomorpihized and macroless 
fn hashmap() -> &'static HashMap<u32, &'static str> {
    static HASHMAP: OnceCell<HashMap<u32, &'static str>> = OnceCell::INIT;
    HASHMAP.get_or_init(|| {
        let mut m = HashMap::new();
        m.insert(0, "foo");
        m.insert(1, "bar");
        m.insert(2, "baz");
        m
    })
}

Guess I am publishing a crate…

11 Likes