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?
answer
- std since 1.80
- deref triggers the closure
- default type parameter fn() -> T
- static must be Sync
basics
~20 sDeclare 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 sSince 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 linesuse 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
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.
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.
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.
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.