Global singletons initialized at program start, an alternative to lazy initialization.
Usage
Simply add magic_static
as a dependency in your Cargo.toml
to get started:
[]
= "*"
bare-metal
If your target doesn't support atomics or threads, enable the bare-metal
feature flag in your Cargo.toml
:
[]
= { = "*", = ["bare-metal"] }
Example
extern crate magic_static;
// You can also modularize your magic statics in a group at the module level like so:
// See `main()` for how to initialize these magic statics.
// You can also decorate statics to make them magic statics
static FOO_BAR: JoinHandle = ;
Comparison to lazy_static
lazy_static
s are initialized on first-use and are targetted towards multithreaded applications.
Every time a lazy_static
is dereferenced, it must check whether it has been initialized yet. This is usually extremely cheap, and the resulting reference can be stored for use in hot loops (for example), but in some cases you may prefer no checks at all, i.e. a more lightweight solution.
magic_static
only performs these checks in debug builds, making it a more ergonomic choice for single-threaded and performance-critical applications.
The downside of using magic_static
is that you must manually initialize each magic_static
in your main
function or somewhere appropriate. See above for an example.