std-type

Rust OnceCell<T>

Use OnceCell for a single-threaded value installed later and then read through a shared reference. Repeated set calls fail while initialized. Exclusive access allows resetting with take, so once refers to an initialization cycle rather than an absolute lifetime prohibition. Expected output (not executed): true A1 true Why: take resets an initialized cell using exclusive access. Common mistake: Assuming set silently replaces the existing value.

Formal Syntax & Structure

rust syntaxrust
OnceCell::new()

Working Example

Example Snippetrust
use std::cell::OnceCell;fn main() {    let mut token = OnceCell::new();    assert!(token.set(String::from("A1")).is_ok());    println!("{}", token.set(String::from("B2")).is_err());    println!("{}", token.take().unwrap());    println!("{}", token.get().is_none());}
Rust Reference