matklad / once_cell

Rust library for single assignment cells and lazy statics without macros
Apache License 2.0
1.84k stars 110 forks source link

Add simple `once!` macro #176

Closed CodesInChaos closed 2 years ago

CodesInChaos commented 2 years ago

Often I want to lazily initialize some global state. I feel that OnceCell/Lazy have an unnecessarily complex API for that. I'd like to add a simple once! macro for this use-case:

macro_rules! once {
    ($init: expr; $t: ty) => {{
        static CELL: ::once_cell::sync::OnceCell<$t> = ::once_cell::sync::OnceCell::<$t>::new();
        CELL.get_or_init(|| $init)
    }}
}

which would be used like:

fn get_example() -> &'static str {
    once!(String::from("a"); String)
}

The requirement to include a type in the macro invocation is unfortunate, but can be made optional once rust supports type inference for statics in a function block.

One thing I particularly like about this macro is that it doesn't directly expose a once_cell based type to the user. This would allow std to include such a macro without committing the the full API surface once_cell would bring with it.

matklad commented 2 years ago

I feel it's best to leave such a feature to a separate helper crate -- the goal of once_cell isn't to provide the most concise API, but to encapsulate unsafety as a reusable primitive.

matklad commented 2 years ago

Closing as out-of-scope!