Rust Reference ยท Standard Library Modules
Rust OnceLock and LazyLock types
Reference for std::sync::OnceLock and LazyLock: thread-safe one-time initialization, get_or_init, set, lazily built statics, panics in initializers and cell variants.
OnceLock<T> is a cell that can be written exactly once and then read from any thread. It starts empty; the first successful set or get_or_init stores a value, and every later read sees that same value. LazyLock<T> builds on it: you give it a function at creation time, and the value is computed on first access. Both are in std::sync and are thread-safe. LazyLock is stable since Rust 1.80, OnceLock since 1.70.
Their main job is global state in a static: a lookup table, compiled configuration or a regular expression that is expensive to build but cheap to use. Before these types existed, people used crates such as lazy_static and once_cell.
use std::sync::LazyLock; static GREETING: LazyLock<String> = LazyLock::new(|| "hello".to_uppercase());
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with io::stdin().read_line()), it gets the next line from this box.
Syntax
impl<T> OnceLock<T> { pub const fn new() -> OnceLock<T>; pub fn get(&self) -> Option<&T>; pub fn get_mut(&mut self) -> Option<&mut T>; pub fn set(&self, value: T) -> Result<(), T>; pub fn get_or_init<F: FnOnce() -> T>(&self, f: F) -> &T; pub fn take(&mut self) -> Option<T>; pub fn into_inner(self) -> Option<T>; } impl<T, F: FnOnce() -> T> LazyLock<T, F> { pub const fn new(f: F) -> LazyLock<T, F>; pub fn force(this: &LazyLock<T, F>) -> &T; } // LazyLock<T, F> implements Deref<Target = T>.
| Name | Description |
|---|---|
value |
For set: the value to store. If the cell is already full, it is returned in the Err. |
f |
The initializer. It runs at most once across all threads. |
this |
LazyLock::force is an associated function (not a method) so it does not clash with methods of T. |
Returns. get returns None while empty. get_or_init always returns a reference to the stored value. LazyLock dereferences to T, so you call T's methods directly.
Errors and panics.
- If the initializer of a
LazyLockpanics, the panic propagates to the caller, and theLazyLockbecomes poisoned: later accesses also panic. - For
OnceLock::get_or_init, a panic in the closure leaves the cell empty and a later call may try again. - Calling
get_or_initon the same cell from inside its own initializer may deadlock or panic. Do not do it.
Usage notes
- Pick
LazyLockwhen the value has one fixed way of being built (a global table). PickOnceLockwhen the value arrives from outside, such as command-line arguments or configuration read inmain. - Blocking. If two threads call
get_or_initat once, one runs the closure and the other waits for it. Everyone then gets the same reference. - No reset. Once set, the value stays until the program ends. Statics are never dropped. Only
take(with&mut self) orinto_innercan remove it. - Single-threaded versions.
std::cell::OnceCellandLazyCellhave the same API without synchronization, for thread-local use or non-staticvalues. - Type of
F. In astatic, the closure must be coercible to a function pointer: it cannot capture variables. That is the defaultF = fn() -> T. - Mutable globals.
LazyLock<Mutex<T>>is a safe pattern for a global that changes. Avoidstatic mut. - Cost after init is one atomic load per access, so it is cheap enough for hot paths.
- Sync requirement.
static X: OnceLock<T>needsT: Sync + Send.
Related
OnceCell,Mutex<T>,Arc<T>,static- Lessons: Thread-local and lazy values, Send and Sync