std-method

OnceLock::set and get: explicit initialization

Set a value explicitly and retrieve it without initiating computation. A second set fails and returns its supplied value. get can return None while initialization is in progress. Expected stdout (not executed): true 7 9 Common mistake: Assuming set overwrites the existing value.

Formal Syntax & Structure

rust syntaxrust
cell.set(value) -> Result<(), T>; cell.get() -> Option<&T>

Working Example

Example Snippetrust
fn main() {    use std::sync::OnceLock;    let c = OnceLock::new();    println!("{}", c.get().is_none());    c.set(7).unwrap();    println!("{} {}", c.get().unwrap(), c.set(9).unwrap_err());}
Rust Reference