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?
answer
- static initialisers are constant contexts
- E0435 on the captured local
- set from main, get everywhere
- first writer wins
basics
~20 sA 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.
solid answer
~40 sA `static` is initialised in a constant context, so its `LazyLock::new(|| ...)` closure can only use other statics and constants. Capturing a local such as the parsed path fails with **E0435** ("attempt to use a non-constant value in a constant"). std's `OnceLock` documentation names exactly this limit: `LazyLock` does not accept extra inputs after `new`. The fix is `static SETTINGS: OnceLock<Settings> = OnceLock::new();`, filled by `main` once it has the path: `SETTINGS.set(load(&path))` returns `Err(value)` if something filled it first, or `SETTINGS.get_or_init(|| load(&path))` keeps an existing value. Readers call `SETTINGS.get()`, which returns `Option<&Settings>`, or `wait()` (Rust 1.86) to block until another thread fills it. Loading errors are handled in `main` before `set`, instead of panicking inside a `LazyLock` closure and poisoning it.
code
rust · 7 linesuse std::sync::LazyLock;
fn main() {
let path = String::from("app.toml");
static SETTINGS: LazyLock<String> = LazyLock::new(|| path.clone());
println!("{}", *SETTINGS);
}go deeper
Know that a static's initialiser cannot use main's local variables, and that OnceLock lets main store a value once for everyone else to read.
Explain E0435 as the constant-context rule, and contrast set returning Err(value) with get_or_init keeping an existing value and skipping its closure.
Move fallible loading into main before set, so errors are reported instead of poisoning a LazyLock, and guard readers with an accessor that fails clearly if used too early.
Weigh a process-wide settings static against passing &Settings explicitly: the global is convenient but cannot be refilled, which constrains tests and reload features.
## The limit of `LazyLock` in a static `static SETTINGS: LazyLock<Settings> = LazyLock::new(|| ...);` is perfect when the closure can compute the value from nothing: a hard-coded table, an environment variable read inside the closure, a fixed file path. It breaks down when the value depends on something only known after the program has started and parsed its input, such as a `--config` path from the command line. The reason is how statics are initialised. The initialiser of a `static` is a **constant context**: rustc must be able to evaluate it before the program runs. The closure inside `LazyLock::new` is not run then, but it is still part of that constant expression, so it cannot refer to a local variable of `main`. Declaring the static inside `main` and capturing `path` fails with **E0435**, "attempt to use a non-constant value in a constant", and rustc even suggests replacing `static` with `let`. A `let` binding would compile, but then it is no longer a global. std's documentation for `OnceLock` describes this exact boundary: `LazyLock` is the convenient option in simple cases, and `OnceLock` "shines" when `LazyLock` is too simple, because `LazyLock` does not allow additional inputs to its function after `LazyLock::new(|| ...)`. ## The `OnceLock` pattern `std::sync::OnceLock<T>` (stable since **Rust 1.70**) is the thread-safe write-once cell. It starts empty, and the code that **has** the inputs fills it: 1. Declare `static SETTINGS: OnceLock<Settings> = OnceLock::new();` (`new` is a `const fn`, so this is a valid static). 2. In `main`, parse arguments, read and validate the file, and handle errors there with ordinary `Result` handling. 3. Store the result with `SETTINGS.set(settings)`, which returns `Result<(), Settings>`: `Ok(())` the first time, `Err(settings)` if the cell was already filled. 4. Read it anywhere with `SETTINGS.get()`, which returns `Option<&Settings>`, typically wrapped in a small accessor that calls `expect` with a clear message. | Need | Method | Returns | |---|---|---| | Fill once, detect a second fill | `set(value)` | `Result<(), T>` | | Fill if empty, keep an existing value | `get_or_init(f)` | `&T` | | Read without waiting | `get()` | `Option<&T>` | | Block until another thread fills it | `wait()` (1.86) | `&T` | ## `set` versus `get_or_init` - **`set`** suits a value computed eagerly in `main`: you learn about a double initialisation through the `Err`, and you get the rejected value back. Calling `.unwrap()` on it turns a double initialisation into a panic, which is sometimes the desired loud failure. - **`get_or_init`** suits code where several paths might initialise, such as tests that install their own settings first: whichever caller gets there first wins, and later closures are not called. std guarantees that, among concurrent callers, only one closure runs (if it does not panic). - **`get_or_try_init`**, which would let a fallible loader return its error, is still unstable in std as of 1.99, so the stable pattern is to do the fallible work before `set`. ## Why this is better than panicking inside a `LazyLock` A `LazyLock` closure cannot return an error to its caller. If loading the file fails, the only option inside the closure is to panic, which **poisons** the `LazyLock`: every later access panics with "LazyLock instance has previously been poisoned". With `OnceLock`, `main` sees the `io::Error`, prints a useful message and exits with a non-zero code, and nothing global is ever half-initialised. `OnceLock` itself is documented as never poisoned: if a `get_or_init` closure panics, the cell simply stays empty. ## Things to watch in review - **Order of initialisation.** Code that reads `SETTINGS.get()` before `main` has called `set` gets `None`. An accessor that calls `expect("settings used before main loaded them")` makes that mistake obvious in tests. - **No mutation through the static.** `get_mut` and `take` need `&mut OnceLock`, which a non-`mut` static cannot provide (rustc reports E0596). Settings that must change at run time need a lock around them, which belongs to the material on threads. - **Tests and globals.** Because a filled `OnceLock` cannot be refilled, tests that need different settings cannot share one process-wide static safely; passing `&Settings` explicitly is often the cleaner design. - **Waiting.** A worker thread that starts before configuration is ready can call `SETTINGS.wait()`, stable since 1.86, which blocks until some thread has filled the cell. ## Why interviewers ask it The question separates candidates who know only the `LazyLock` idiom from those who understand its constant-context limit, can read E0435, and know the `OnceLock` API well enough to choose between `set` and `get_or_init` and to keep error handling out of a global initialiser.
- When would you choose `get_or_init` over `set` for a settings `OnceLock`?When more than one path may legitimately initialise it and the first should win, for example a test installing its own settings before the code under test runs. `get_or_init` keeps an existing value and skips the closure, while `set` reports the conflict through `Err` and hands the rejected value back.
- Why not just panic inside a `LazyLock` closure when the settings file is missing?The panic surfaces at whatever code first touches the static, far from start-up, and it poisons the `LazyLock`, so every later access panics too. Loading in `main` lets you report the `io::Error` cleanly and exit, and the `OnceLock` is only filled with a valid value.
- What does `OnceLock::wait` add, and since when is it stable?`wait`, stable since Rust 1.86, blocks the calling thread until the cell has been filled by someone else and then returns `&T`. It suits worker threads that start before configuration is loaded, where `get` would return `None` and `get_or_init` would start a second, competing load.
- A static LazyLock closure can capture locals because it runs later
- OnceLock set silently replaces the earlier settings
- OnceLock get_mut lets you reload settings through the static
- get_or_try_init is the stable way to load fallibly
- OnceLock is poisoned if the initialiser panics
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.