한 번만 쓸 수 있는 synchronization primitive (기본 요소)이다. static하고 thread-safe하다.
use std::sync::OnceLock;
static CELL: OnceLock<String> = OnceLock::new();
assert!(CELL.get().is_none());
std::thread::spawn(|| {
let value: &String = CELL.get_or_init(|| {
"Hello, World!".to_string()
});
assert_eq!(value, "Hello, World!");
}).join().unwrap();
let value: Option<&String> = CELL.get();
assert!(value.is_some());
assert_eq!(value.unwrap().as_str(), "Hello, World!");
underlying value의 mutable reference를 얻는다. cell이 비어 있다면, None을 반환한다.
content를 value로 정한다. 만약 다른 thread가 initialize하려고 하면 막는다. 문제 없이 set된다면 Ok(())를 반환한다.
cell의 내용을 get한다. 만약 cell이 비어 있다면, f로 initialize한다.
use std::sync::OnceLock;
let cell = OnceLock::new();
let value = cell.get_or_init(|| 92);
assert_eq!(value, &92);
let value = cell.get_or_init(|| unreachable!());
assert_eq!(value, &92);