pub struct OnceLock<T> { /* private fields */ }
Expand description
The OnceLock
is a synchronization primitive that allows for
initializing a value once, and allowing others to .await
a
reference to the value. This is useful for lazy initialization of
a static value.
Note: this implementation uses a busy loop to poll the value,
which is not as efficient as registering a dedicated Waker
.
However, if the usecase for it is to initialize a static variable
relatively early in the program life cycle, it should be fine.
§Example
use futures_executor::block_on;
use embassy_sync::once_lock::OnceLock;
// Define a static value that will be lazily initialized
static VALUE: OnceLock<u32> = OnceLock::new();
let f = async {
// Initialize the value
let reference = VALUE.get_or_init(|| 20);
assert_eq!(reference, &20);
// Wait for the value to be initialized
// and get a static reference it
assert_eq!(VALUE.get().await, &20);
};
block_on(f)
Implementations§
Source§impl<T> OnceLock<T>
impl<T> OnceLock<T>
Sourcepub async fn get(&self) -> &T
pub async fn get(&self) -> &T
Get a reference to the underlying value, waiting for it to be set. If the value is already set, this will return immediately.
Sourcepub fn try_get(&self) -> Option<&T>
pub fn try_get(&self) -> Option<&T>
Try to get a reference to the underlying value if it exists.
Sourcepub fn init(&self, value: T) -> Result<(), T>
pub fn init(&self, value: T) -> Result<(), T>
Set the underlying value. If the value is already set, this will return an error with the given value.
Sourcepub fn get_or_init<F>(&self, f: F) -> &Twhere
F: FnOnce() -> T,
pub fn get_or_init<F>(&self, f: F) -> &Twhere
F: FnOnce() -> T,
Get a reference to the underlying value, initializing it if it does not exist.
Sourcepub fn into_inner(self) -> Option<T>
pub fn into_inner(self) -> Option<T>
Consume the OnceLock
, returning the underlying value if it was initialized.