pub struct LazyLock<T, F = fn() -> T> { /* private fields */ }full and non-crate feature use_std only.Expand description
A value which is initialized on the first access.
This type is a thread-safe LazyCell, and can be used in statics.
Since initialization may be called from multiple threads, any
dereferencing call will block the calling thread if another
initialization routine is currently running.
§Poisoning
If the initialization closure passed to LazyLock::new panics, the lock will be poisoned.
Once the lock is poisoned, any threads that attempt to access this lock (via a dereference
or via an explicit call to force()) will panic.
§Examples
Initialize static variables with LazyLock.
use kernel_api::sync::LazyLock;
// Note: static items do not call [`Drop`] on program termination, so this won't be deallocated.
static DEEP_THOUGHT: LazyLock<String> = LazyLock::new(|| {
another_crate::great_question()
});
// The `String` is built, stored in the `LazyLock`, and returned as `&String`.
let _ = &*DEEP_THOUGHT;Initialize fields with LazyLock.
use kernel_api::sync::LazyLock;
#[derive(Debug)]
struct UseCellLock {
number: LazyLock<u32>,
}
fn main() {
let lock: LazyLock<u32> = LazyLock::new(|| 0u32);
let data = UseCellLock { number: lock };
assert_eq!(*data.number, 0);
}Implementations§
Source§impl<T, F: FnOnce() -> T> LazyLock<T, F>
impl<T, F: FnOnce() -> T> LazyLock<T, F>
Sourcepub const fn new(f: F) -> Self
pub const fn new(f: F) -> Self
Creates a new lazy value with the given initializing function.
§Examples
use kernel_api::sync::LazyLock;
let hello = "Hello, World!".to_string();
let lazy = LazyLock::new(|| hello.to_uppercase());
assert_eq!(&*lazy, "HELLO, WORLD!");Sourcepub fn force(this: &Self) -> &T
pub fn force(this: &Self) -> &T
Forces the evaluation of this lazy value and returns a reference to
result. This is equivalent to the Deref impl, but is explicit.
This method will block the calling thread if another initialization routine is currently running.
§Panics
If the initialization closure panics (the one that is passed to the new() method), the
panic is propagated to the caller, and the lock becomes poisoned. This will cause all future
accesses of the lock (via force() or a dereference) to panic.
§Examples
use kernel_api::sync::LazyLock;
let lazy = LazyLock::new(|| 92);
assert_eq!(LazyLock::force(&lazy), &92);
assert_eq!(&*lazy, &92);