I’ve been using lazy_static until now but was trying to migrate to OnceCell. It seems I can’t have a OnceCell<Regex> even though I’m never calling mutable methods on the regex. I’m not even using multiple threads.
The error I’m getting is:
Any way to solve this or do I have to use OnceLock / continue using lazy_static? I don’t want to add the overhead of using OnceLock if not necessary.
First of all, thank you for this very elaborate answer. So that means OnceCell can never be used in a static but only as local variable / member variable? I see, that makes sense and also reduces its use cases by a lot of what I initially thought. But your example makes sense and the name/package also suggest it’s not thread-safe in itself, I had just wrongly assumed OnceCell was meant to be used in static contexts.
Thanks!
Yeah, it doesn’t help that in the
once_cell
crate, the thread-safe version was also calledOnceCell
; you had to choose betweenonce_cell::sync::OnceCell
andonce_cell::unsync::OnceCell
. But when it was added to the standard library,once_cell::sync::OnceCell
was renamed toOnceLock
to make them easier distinguishable. So