Skip to main content

Module once

Module once 

Source
Expand description

Lazy, one-time initialization on top of generic_static.

generic_static. only supports bytemuck::Zeroable types, so the storage is always zeroed. That allows Atomic*, UnsafeCell, Cell, and other similar types to be stored — but not types that need a non-zero initial value.

OnceSlot allows to store non Zeroable types as a generic static: It is itself zeroable, but it can be lazily initialized provided by initializer closure into OnceSlot::get_or_init

use static_generics::{define_namespace, namespace::NamespaceExt};

define_namespace!(MyNs);

struct Config {
    retries: u32,
}

let cfg = MyNs::once::<Config>(|| Config { retries: 3 });
assert_eq!(cfg.retries, 3);
// Second call ignores the closure and returns the same address.
let again = MyNs::once::<Config>(|| Config { retries: 99 });
assert!(core::ptr::eq(cfg, again));

Structs§

OnceSlot
Zero-initialized slot for one-time initialization of a T.