4个版本
| 0.1.3 | 2023年4月20日 | 
|---|---|
| 0.1.2 | 2022年6月30日 | 
| 0.1.1 | 2022年6月30日 | 
| 0.1.0 | 2022年6月30日 | 
#2786 在 Rust模式
7KB
84 行
Maybe static
以惰性方式初始化带有参数的静态变量。
简单使用示例
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());
}
该宏将创建一个局部静态变量,它只初始化一次,并且完全线程安全。
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
}
第一次初始化需要Some。
fn main() {
    println!("{}", get_lazy(None).unwrap()); // Error!
}
通过作用域创建新的唯一值。
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
}
最初在maybeuninit博客文章中开发。