matklad / once_cell

Rust library for single assignment cells and lazy statics without macros

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Add simple `once!` macro

CodesInChaos opened this issue · comments

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.

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.

Closing as out-of-scope!