std-type

OnceLock: shared one-time value

Store a value initialized on demand, even with multiple callers. Successful initialization is shared; a panic in initialization does not permanently poison OnceLock. Avoid recursively initializing the same cell. Expected stdout (not executed): ready ready Common mistake: Assuming later initializers replace the stored value.

Formal Syntax & Structure

rust syntaxrust
OnceLock::new(); cell.get_or_init(F)

Working Example

Example Snippetrust
fn main() {    use std::sync::OnceLock;    let c = OnceLock::new();    let a = c.get_or_init(|| String::from("ready"));    let b = c.get_or_init(|| String::from("ignored"));    println!("{} {}", a, b);}
Rust Reference