skip to content

OnceCell and LazyLock

OnceCell and OnceLock initialise a value once, and LazyCell and LazyLock run the initialiser on first use. Interviewers ask how to build a global without lazy_static.

on this pageshow

questions

6

In current Rust, how do you declare a global value built on first use, such as a table of compiled regexes, without the `lazy_static!` macro?

level: middleimportance: must knowfreq 55%

answer

  1. std since 1.80
  2. deref triggers the closure
  3. default type parameter fn() -> T
  4. static must be Sync

basics

~20 s

Declare static RULES: LazyLock<T> = LazyLock::new(|| ...) using std::sync::LazyLock, stable since Rust 1.80. The closure runs once, on the first dereference by whichever thread arrives first, and every later access gets a shared reference to the stored value.

solid answer

~40 s

Since Rust 1.80 the standard library has `std::sync::LazyLock`, so a global built on first use is just `static RULES: LazyLock<Vec<(&str, Regex)>> = LazyLock::new(|| ...);`. `LazyLock::new` is a `const fn` that only stores the closure; the closure runs on the first dereference (`RULES.iter()`, `&*RULES` or `LazyLock::force`), exactly once, and other threads that arrive during initialisation block until it finishes. You do not name the closure type because `LazyLock<T, F = fn() -> T>` defaults `F` to a function pointer and a non-capturing closure coerces to it. The static must be `Sync`, which `LazyLock<T>` is when `T: Send + Sync`. This replaces `lazy_static!`'s `static ref` syntax and the `once_cell` crate's `sync::Lazy`, which is the same design that std adopted.

code

rust · 21 lines
rust
use regex::Regex;
use std::sync::LazyLock;

// One process-wide table, compiled on first use by whichever thread gets there first.
static RULES: LazyLock<Vec<(&'static str, Regex)>> = LazyLock::new(|| {
    println!("compiling rules");
    vec![
        ("ipv4", Regex::new(r"^\d{1,3}(\.\d{1,3}){3}$").unwrap()),
        ("uuid", Regex::new(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$").unwrap()),
    ]
});

fn classify(input: &str) -> Option<&'static str> {
    RULES.iter().find(|(_, re)| re.is_match(input)).map(|(name, _)| *name)
}

fn main() {
    println!("before first use");
    println!("{:?}", classify("10.0.0.1"));
    println!("{:?}", classify("not-an-id"));
}

go deeper

for a junior

Know the shape static NAME: LazyLock<T> = LazyLock::new(|| ...) and that the value is built the first time it is used, not at program start.

for a middle

Explain why the closure type disappears (default fn() -> T parameter), why the static must be Sync, and that other threads block while the first one initialises.

for a senior

Review such globals for panics in the closure, which poison the LazyLock, and prefer an explicit OnceLock filled by main when the input comes from outside.

for a principal

Treat migration from lazy_static and once_cell as dependency hygiene gated by the crate's minimum supported Rust version, since std has covered the same ground since 1.80.

## The problem: statics are initialised at compile time A Rust `static` item must be initialised by a **constant expression**. You cannot write `static RULES: Vec<Regex> = build();`: rustc rejects it with **E0015** ("cannot call non-const function `build` in statics"). Heap allocation, parsing and regex compilation are run-time work, so for years the ecosystem used crates to defer that work to first use: - **`lazy_static!`**, a macro with a `static ref NAME: T = expr;` syntax that generated a hidden type implementing `Deref`. - **`once_cell`**, whose `once_cell::sync::Lazy<T>` and `once_cell::unsync::Lazy<T>` types did the same job without a macro. The `once_cell` design was adopted into std in two steps: `OnceCell` and `OnceLock` in **Rust 1.70** (June 2023), and `LazyCell` and `LazyLock` in **Rust 1.80** (July 2024). On any toolchain from 1.80 on, a new global needs neither crate. ## The std idiom ```rust use std::sync::LazyLock; static RULES: LazyLock<Vec<(&'static str, Regex)>> = LazyLock::new(|| { vec![("ipv4", Regex::new(r"^\d{1,3}(\.\d{1,3}){3}$").unwrap())] }); ``` Three things make this compile and behave correctly: 1. **`LazyLock::new` is a `const fn`.** It does not call the closure; it only stores it, which is a constant-time operation rustc can evaluate when building the static. 2. **The closure type has a default.** `LazyLock<T, F = fn() -> T>` defaults its second parameter to a function pointer. A closure that **captures nothing** coerces to `fn() -> T`, so the static's type can be written as `LazyLock<T>`. You could not write the closure type yourself: `impl Trait` is not allowed in a static's type (**E0562**). 3. **The static must be `Sync`.** Every shared `static` needs a `Sync` type. `LazyLock<T, F>` is `Sync` when `T: Send + Sync` and `F: Send`, so a table of compiled regexes qualifies, while `LazyLock<Cell<u32>>` does not. ## When and how the closure runs - The closure runs on the **first access through `Deref`** (a method call like `RULES.iter()`, an explicit `&*RULES`) or through **`LazyLock::force(&RULES)`**. There is no code before `main`: Rust has no static constructors, so nothing runs at program start. - It runs **once**. Internally `LazyLock` holds a `std::sync::Once` plus storage for either the closure or the value. - If another thread dereferences the static while initialisation is in progress, that thread **blocks** until the value is ready; it never runs a second copy of the closure. - After initialisation, access is a cheap check of the `Once` state followed by a shared `&T`. - Since **Rust 1.94**, `LazyLock::get(&RULES)` returns `Option<&T>` without forcing initialisation, which is handy for diagnostics. | Old code | Std replacement | |---|---| | `lazy_static! { static ref X: T = expr; }` | `static X: LazyLock<T> = LazyLock::new(\|\| expr);` | | `once_cell::sync::Lazy<T>` | `std::sync::LazyLock<T>` | | `once_cell::unsync::Lazy<T>` | `std::cell::LazyCell<T>` | | `once_cell::sync::OnceCell<T>` | `std::sync::OnceLock<T>` | ## Things to know when reviewing such a global - **Statics are never dropped.** std's own documentation notes that a `static` does not run `Drop` at program exit, so a `LazyLock<Vec<Regex>>` is reclaimed by the operating system, not by its destructor. Leak checkers may report it; that is expected. - **Failure inside the closure is a panic.** A `LazyLock` closure cannot return a `Result` to the caller; an `unwrap` on a bad pattern panics on first use and **poisons** the `LazyLock`, so every later access panics too. Patterns known at compile time are safe to `unwrap`; data loaded from outside is a better fit for an explicit `OnceLock` that `main` fills after handling the error. - **Mutation is a separate concern.** `LazyLock` hands out `&T`. If the global must change after start-up, wrapping the value in a lock is the material on threads and mutexes, not this type. - **Migration is mechanical.** Replacing `once_cell::sync::Lazy` with `std::sync::LazyLock` keeps semantics, including poisoning on panic, and removes a dependency. The main reason to keep `once_cell` is a minimum supported Rust version below 1.80, or a need for APIs std has not stabilised, such as `get_or_try_init`. ## Why interviewers ask it It is the modern answer to a very old question ("how do I make a global `HashMap` or regex in Rust?"). A strong answer names `LazyLock` and its release, explains why the closure type disappears, says when initialisation happens and on which thread, and knows the `Sync` requirement and the panic behaviour.

  • Why does `LazyLock::new(|| ...)` work in a `static` even though the closure does heavy run-time work?
    `LazyLock::new` is a `const fn` that only moves the closure into the `LazyLock`; it never calls it. The closure, coerced to the default `fn() -> T` parameter, is stored and run later, on the first dereference. Calling the work directly in the initialiser would fail with E0015.
  • Which threads can run the initialiser of a `static LazyLock`, and what do the others do?
    Whichever thread dereferences it first runs the closure, once. A thread that arrives while initialisation is in progress blocks until the value is stored, then reads it. Threads arriving later see the finished value immediately. No thread runs a second copy of the closure.
  • What still makes the `once_cell` crate worth keeping in a project?
    A minimum supported Rust version below 1.80 (or 1.70 for the once types), or APIs std has not stabilised as of 1.99, such as `get_or_try_init` for a fallible initialiser. Otherwise `std::sync::LazyLock` and `OnceLock` cover the same ground without a dependency.

  • LazyLock initialisers run before main like static constructors
  • You still need lazy_static or once_cell for a lazy global
  • LazyCell works in a static just like LazyLock
  • The closure reruns on every access to the static
  • A static LazyLock can capture local variables from main

Assumes Rust 1.99 on the 2024 edition; OnceCell and OnceLock are stable since 1.70 and LazyCell and LazyLock since 1.80, so older toolchains need the once_cell crate.

open as a page

In Rust, how does `std::cell::OnceCell` let you fill a value once through a shared reference, and what do `get`, `set` and `get_or_init` return?

level: juniorimportance: should knowfreq 40%

basics

~20 s

OnceCell<T>, stable since Rust 1.70, starts empty and can be written exactly once through &self. get returns Option<&T>, get_or_init runs its closure only while the cell is empty and returns &T, and set returns Err(value) if a value is already stored.

open as a page

In Rust, why does rustc reject a `static` of type `LazyCell` or `OnceCell` but accept `LazyLock` and `OnceLock`, and when is each pair the right choice?

level: middleimportance: should knowfreq 30%

basics

~20 s

A shared static must be Sync. LazyCell and OnceCell are not, so rustc reports E0277; LazyLock and OnceLock synchronise the first write and are Sync for Send + Sync values. Use the Lock pair for globals and the Cell pair on one thread.

open as a page

A Rust service loads its settings file from a path given on the command line; why can't a `static LazyLock` do this, and how does `OnceLock` handle it?

level: seniorimportance: should knowfreq 30%

basics

~20 s

A static LazyLock's closure cannot capture main's local path, because a static initialiser is a constant context and rustc reports E0435. Declare static SETTINGS: OnceLock<Settings>, have main call set or get_or_init with the loaded value, and read it elsewhere with get.

open as a page

As a Rust lead, when do you allow a process-wide `LazyLock` or `OnceLock` global in a service, and when do you require passing state explicitly?

level: principalimportance: should knowfreq 32%

basics

~20 s

Allow a global when the value is immutable and self-contained, such as a table of compiled patterns or a process-wide facility set once at startup. Require explicit passing, usually an Arc<Config> field or a parameter, for anything tests vary, anything per tenant or request, and anything that holds mutable state.

open as a page

In Rust, what happens to a `LazyLock` or an `OnceLock` when its initialiser panics, and what happens when an initialiser reenters the same cell?

level: seniorimportance: nice to knowfreq 20%

basics

~20 s

A panicking LazyLock or LazyCell initialiser poisons it, so every later access panics. A panicking OnceLock or OnceCell get_or_init leaves the cell empty, so the next call retries. Reentrant initialisation panics for OnceCell and currently deadlocks for OnceLock.

open as a page