maybe_static 0.1.3

Initialize a lazy static with params, create Meyer's singleton
Documentation
  • Coverage
  • 100%
    3 out of 3 items documented1 out of 1 items with examples
  • Size
  • Source code size: 6.19 kB This is the summed size of all the files inside the crates.io package for this release.
  • Documentation size: 1.08 MB This is the summed size of all files generated by rustdoc for all configured targets
  • Ø build duration
  • this release: 9s Average build duration of successful builds.
  • all releases: 9s Average build duration of successful builds in releases after 2024-10-23.
  • Links
  • adrien-zinger/maybe_static
    1 0 0
  • crates.io
  • Dependencies
  • Versions
  • Owners
  • adrien-zinger

Maybe static

Initialize in a lazy way a static variable with parameters.

Example of a simple usage:

use maybe_static::maybe_static;

pub fn get_lazy(opt: Option<(&str, &str)>) -> Result<&'static String, &'static str> {
    maybe_static!(opt, String, |(a, b)| format!("{a}:{b}"))
}

fn main() {
    println!("{}", get_lazy(Some(("hello", "world"))).unwrap());
    println!("{}", get_lazy(None).unwrap());
}

The macro will create a local static variable that is initialized once, ONLY ONCE. It's also totally thread safe.

fn main() {
    println!("{}", get_lazy(Some(("hello", "world"))).unwrap());
    // print hello:world (initialize)
    println!("{}", get_lazy(None).unwrap());
    // print hello:world
    println!("{}", get_lazy(Some(("foo", "bar"))).unwrap());
    // still print hello:world
}

Require a Some for the first initialization.

fn main() {
    println!("{}", get_lazy(None).unwrap()); // Error!
}

Create a new unique value by scope.

fn main() {
    let a = maybe_static!(Some(("hello", "world")), String, |(a, b)| format!(
        "{a}:{b}"
    ))
    .unwrap();
    let b = maybe_static!(Some(("foo", "bar")), String, |(a, b)| format!(
        "{a}:{b}"
    ))
    .unwrap();
    println!("{a}\n{b}")
    // hello:world
    // foo:bar


    for i in 0..3 {
        print!("{}", maybe_static!(Some(i), usize, |i| i).unwrap());
    }
    // 000
}

Initially developed around the article in the maybeuninit blog