pub struct OnceLock<T> { /* private fields */ }full and non-crate feature use_std only.Expand description
A synchronization primitive which can nominally be written to only once.
This type is a thread-safe OnceCell, and can be used in statics.
In many simple cases, you can use LazyLock<T, F> instead to get the benefits of this type
with less effort: LazyLock<T, F> “looks like” &T because it initializes with F on deref!
Where OnceLock shines is when LazyLock is too simple to support a given case, as LazyLock
doesn’t allow additional inputs to its function after you call LazyLock::new(|| ...).
A OnceLock can be thought of as a safe abstraction over uninitialized data that becomes
initialized once written.
Implementations§
Source§impl<T> OnceLock<T>
impl<T> OnceLock<T>
Sourcepub fn get(&self) -> Option<&T>
pub fn get(&self) -> Option<&T>
Gets the reference to the underlying value.
Returns None if the cell is uninitialized, or being initialized.
This method never blocks.
Sourcepub fn get_mut(&mut self) -> Option<&mut T>
pub fn get_mut(&mut self) -> Option<&mut T>
Gets the mutable reference to the underlying value.
Returns None if the cell is uninitialized.
This method never blocks. Since it borrows the OnceLock mutably,
it is statically guaranteed that no active borrows to the OnceLock
exist, including from other threads.
Sourcepub fn get_or_init(&self, f: impl FnOnce() -> T) -> &T
pub fn get_or_init(&self, f: impl FnOnce() -> T) -> &T
Gets the contents of the cell, initializing it to f() if the cell
was uninitialized.
Many threads may call get_or_init concurrently with different
initializing functions, but it is guaranteed that only one function
will be executed if the function doesn’t panic.
§Panics
If f() panics, the panic is propagated to the caller, and the cell
remains uninitialized.
It is an error to reentrantly initialize the cell from f. The
exact outcome is unspecified.
§Examples
use kernel_api::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);