On this page
  1. OnceLock
  2. Signature & Overview
  3. Notes & Pitfalls
  4. Example

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

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