On this page
OnceLock
Prev: `mpsc` | Up: sync | Next: `AtomicUsize`
Rel: sync, rust/builtins
Ref: Rust std — OnceLock
Tags: #public #prog #rust #stdlib #sync #tier/standard
Signature & Overview
OnceLock<T> /* + LazyLock<T> */
Thread-safe one-time initialization cell for global singletons without unsafe or external crates.
Notes & Pitfalls
- Thread-safe one-time lazy initialization (Rust 1.70+): Replaces
once_cell::sync::OnceCellfor global config, regexes, or singletons. - Also see
LazyLock<T>(Rust 1.80+) when the initializer doesn't need runtime arguments.
Example
use std::sync::OnceLock;
static CONFIG: OnceLock<String> = OnceLock::new();
fn main() {
let val = CONFIG.get_or_init(|| String::from("initialized-once"));
assert_eq!(val, "initialized-once");
assert_eq!(CONFIG.get().map(String::as_str), Some("initialized-once"));
}
Linked from
Related notes
- tuts/rust/std/sync/AtomicUsize Linked here; links to this page; shared tags: #prog, #rust, #stdlib, #sync, #tier
- tuts/rust/std/sync/mpsc Linked here; links to this page; shared tags: #prog, #rust, #stdlib, #sync, #tier
- tuts/rust/std/sync Linked here; links to this page; shared tags: #prog, #rust, #stdlib, #sync
- tuts/rust/builtins Linked here; shared tags: #prog, #rust
- tuts/rust/std/sync/Mutex shared tags: #prog, #rust, #stdlib, #sync, #tier
- tuts/rust/std/sync/RwLock shared tags: #prog, #rust, #stdlib, #sync, #tier
- tuts/rust/std/collections/BinaryHeap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/BTreeMap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/HashMap shared tags: #prog, #rust, #stdlib, #tier
- tuts/rust/std/collections/HashSet shared tags: #prog, #rust, #stdlib, #tier