pub struct OnceCell<T> { /* private fields */ }Expand description
A cell which can nominally be written to only once.
This allows obtaining a shared &T reference to its inner value without copying or replacing
it (unlike Cell), and without runtime borrow checks (unlike RefCell). However,
only immutable references can be obtained unless one has a mutable reference to the cell
itself. In the same vein, the cell can only be re-initialized with such a mutable reference.
For a thread-safe version of this struct, see std::sync::OnceLock.
§Examples
use std::cell::OnceCell;
let cell = OnceCell::new();
assert!(cell.get().is_none());
let value: &String = cell.get_or_init(|| {
"Hello, World!".to_string()
});
assert_eq!(value, "Hello, World!");
assert!(cell.get().is_some());