#macro-based #lazy-evaluation #static

slazy

A simple, small, no-std, macro-based lazy static library for Rust

1 unstable release

0.1.0 Nov 28, 2023

#9 in #macro-based

MIT license

5KB

SLazy 💄

License GitHub issues Build status

A simple, small, no-std, macro-based lazy static library for Rust.

[Request a feature/report a bug]

Installation

cargo add slazy or by adding the following to your Cargo.toml:

[dependencies]
slazy = "*"

Examples

use slazy::slazy;

slazy! {
    pub FOO: u32 = {
        println!("Evaluating FOO");
        42
    };

    BAR: u32 = 1337;
}

println!("FOO: {}", *FOO); // Evaluates FOO
println!("{}", *FOO); // Gets the value of FOO without evaluating it again
println!("{}", *BAR); // Evaluates BAR

Thread safety

[!WARNING] If you want to use SLazy in a multi-threaded environment, you should initialize the lazy statics before spawning any threads. This is because the lazy statics might not be thread safe in certain scenarios due to data races.

Example

use slazy::{slazy, init};

slazy! {
    pub FOO: u32 = {
        println!("Evaluating FOO");
        42
    };
}

init!(FOO); // or `_ = *FOO;`

std::thread::spawn(|| {
    println!("{}", *FOO); // Safe to use FOO in this thread
});

License

This project is licensed under the MIT license.

No runtime deps