rust-lang-nursery / lazy-static.rs

A small macro for defining lazy evaluated static variables in Rust.
Apache License 2.0
1.9k stars 111 forks source link

Lazy static with custom attribute #126

Closed real-felix closed 1 year ago

real-felix commented 5 years ago

Is it planed to have a custom attribute for lazy static? For example:

#[lazy] static ref HASHMAP: HashMap<u32, &'static str> = {
    let mut m = HashMap::new();
    m.insert(0, "foo");
    m.insert(1, "bar");
    m.insert(2, "baz");
    m
};
KodrAus commented 5 years ago

Hi @Boiethios, since the lazy_static macro lies about its type in the declaration I think we could create more confusion by not having it explicitly wrapped in a macro, where you can expect to be outside the realms of standard Rust syntax.

As another alternative, I personally like the API from #111 where the macro moves just to the body of the static declaration:

static GLOBAL_DATA: Lazy<Mutex<HashMap<i32, String>>> = sync_lazy! {
    let mut m = HashMap::new();
    m.insert(13, "Spica".to_string());
    m.insert(74, "Hoyten".to_string());
    Mutex::new(m)
};

Moving away from a wrapper macro like your suggestion, or the one from #111, does have the benefit of being understandable by tooling as just a normal static declaration rather than a block-box macro.