pub struct LazyLock<T, F = fn() -> T> { /* private fields */ }
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.
§Examples
Initialize static variables with LazyLock
.
use std::sync::LazyLock;
// n.b. static items do not call [`Drop`] on program termination, so this won't be deallocated.
// this is fine, as the OS can deallocate the terminated program faster than we can free memory
// but tools like valgrind might report "memory leaks" as it isn't obvious this is intentional.
static DEEP_THOUGHT: LazyLock<String> = LazyLock::new(|| {
// M3 Ultra takes about 16 million years in --release config
another_crate::great_question()
});
// The `String` is built, stored in the `LazyLock`, and returned as `&String`.
let _ = &*DEEP_THOUGHT;
Initialize fields with LazyLock
.
Implementations§
source§impl<T, F: FnOnce() -> T> LazyLock<T, F>
impl<T, F: FnOnce() -> T> LazyLock<T, F>
1.80.0 (const: 1.80.0) · sourcepub const fn new(f: F) -> LazyLock<T, F>
pub const fn new(f: F) -> LazyLock<T, F>
Creates a new lazy value with the given initializing function.
§Examples
sourcepub fn into_inner(this: Self) -> Result<T, F>
🔬This is a nightly-only experimental API. (lazy_cell_into_inner
#125623)
pub fn into_inner(this: Self) -> Result<T, F>
lazy_cell_into_inner
#125623)Consumes this LazyLock
returning the stored value.
Returns Ok(value)
if Lazy
is initialized and Err(f)
otherwise.
§Examples
sourcepub fn force_mut(this: &mut LazyLock<T, F>) -> &mut T
🔬This is a nightly-only experimental API. (lazy_get
#129333)
pub fn force_mut(this: &mut LazyLock<T, F>) -> &mut T
lazy_get
#129333)Forces the evaluation of this lazy value and returns a mutable reference to the result.
§Examples
source§impl<T, F> LazyLock<T, F>
impl<T, F> LazyLock<T, F>
sourcepub fn get_mut(this: &mut LazyLock<T, F>) -> Option<&mut T>
🔬This is a nightly-only experimental API. (lazy_get
#129333)
pub fn get_mut(this: &mut LazyLock<T, F>) -> Option<&mut T>
lazy_get
#129333)Returns a reference to the value if initialized, or None
if not.
§Examples
Trait Implementations§
impl<T: RefUnwindSafe + UnwindSafe, F: UnwindSafe> RefUnwindSafe for LazyLock<T, F>
impl<T: Sync + Send, F: Send> Sync for LazyLock<T, F>
impl<T: UnwindSafe, F: UnwindSafe> UnwindSafe for LazyLock<T, F>
Auto Trait Implementations§
impl<T, F = fn() -> T> !Freeze for LazyLock<T, F>
impl<T, F> Send for LazyLock<T, F>
impl<T, F> Unpin for LazyLock<T, F>
Blanket Implementations§
source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more