Lazy_static vs once_cell::sync::OnceCell

Ever since I got serious about Rust, if I need to initialize something exactly once I've been using the lazy_static crate, which works quite well.

But the last couple of months I've seen OnceCell pop up every now and again.
It seems to be advertised as a macro-less version of lazy_static, and indeed I can see that they both can server the use case I mentioned above.

My question is, other than the fact that one is a macro and the other is not, why should I care, or why should I prefer OnceCell over lazy_static?

Notably, the functionality of once_cell is being considered for inclusion in std (and it's already there in nightly behind the once_cell feature gate):

Assuming that proposal is accepted and stabilized, switching your code to std::sync::Lazy from the once_cell crate will presumably be simpler than switching from lazy_static.

The once_cell docs also point out that once_cell::Lazy can be used within a function, where lazy_static! can only be used globally: once_cell - Rust once_cell::Lazy can be used with local variables, unlike lazy_static!.

I see, thank you for your answer.

However, lazy_static most decidedly can be used in functions and methods. I regularly do that to control access scope for regexes.

1 Like

Sorry, you're quite right. The actual difference is that once_cell::Lazy, unlike lazy_static!, can capture/refer to local variables.

1 Like

Okay, that definitely could be useful every now and again.