pub struct Global<T> { /* private fields */ }Expand description
Ergonomic global variables.
No more Mutex<Option<...>> shenanigans with lazy initialization on each use site, or OnceLock which limits to immutable access.
This type is very similar to once_cell::Lazy in its nature,
with a minimalistic implementation. Unlike Lazy, it is only designed for global variables, not for local lazy initialization
(following “do one thing and do it well”).
Global<T> features:
constconstructors, allowing to be used instaticvariables withoutOption.- Initialization function provided in constructor, not in each use site separately.
- Ergonomic access through guards to both
&Tand&mut T. - Completely safe usage. Little use of
unsafein the implementation (for performance reasons).
There are two const methods for construction: new() and default().
For access, you should primarily use lock(). There is also try_lock() for special cases.
Implementations§
Source§impl<T> Global<T>
impl<T> Global<T>
Sourcepub const fn new(init_fn: fn() -> T) -> Self
pub const fn new(init_fn: fn() -> T) -> Self
Create Global<T>, providing a lazy initialization function.
The initialization function is only called once, when the global is first accessed through lock().
Sourcepub const fn default() -> Selfwhere
T: Default,
pub const fn default() -> Selfwhere
T: Default,
Create Global<T> with T::default() as initialization function.
This is inherent rather than implementing the Default trait, because the latter is not const and thus useless in static contexts.
Sourcepub fn lock(&self) -> GlobalGuard<'_, T>
pub fn lock(&self) -> GlobalGuard<'_, T>
Returns a guard that gives shared or mutable access to the value.
Blocks until the internal mutex is available.
§Panics
If the initialization function panics. Once that happens, the global is considered poisoned and all future calls to lock() will panic.
This can currently not be recovered from.
Sourcepub fn try_lock(&self) -> Result<GlobalGuard<'_, T>, GlobalLockError<'_, T>>
pub fn try_lock(&self) -> Result<GlobalGuard<'_, T>, GlobalLockError<'_, T>>
Non-blocking access with error introspection.