全局静态变量初化,在他编程语言里面,是一个很简单又自然的事,然而在rust里面并非容易。如果像下面定义全局静态变量,那么会报错:

1
2
static ref VEC_VAL: Vec<String> = vec!["1, 2, 3".into()];

静态变量不允许动态分配内存:

1
2
3
4
5
6
7
error[E0010]: allocations are not allowed in statics
 --> bin/lazy_static.rs:5:29
  |
5 | static VEC_VAL: Vec<String> = vec!["1, 2, 3".into()];
  |                             ^^^^^^^^^^^^^^^ allocation not allowed in statics
  |
  = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)

lazy_static提供一种初始化静态全局变量的方式,通过lazy_static宏,全局静态变量被延迟到第一次调用时才初始化,并只初始化一次。lazy_static宏,匹配的是static ref,所以定义的静态变量都是不可变引用。如:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
use std::collections::HashMap;

#[macro_use]
extern crate lazy_static;

lazy_static! {
    static ref INT_VAL: i32 = 10;
    static ref VEC_VAL: Vec<String> = vec!["1, 2, 3".into()];

    static ref MAP_VAL: HashMap<String, String> = {
        let mut map = HashMap::new();
        map.insert("Hello".into(), "world".into());
        map.insert("F*k".into(), "me".into());
        map
    };
}
fn main() {
    println!("{}, {:?}", *INT_VAL, *VEC_VAL);
    MAP_VAL.iter().for_each(|(k, v)| {
        println!("key={}, value={}", k, v);
    })
}

输出:

1
2
3
10, ["1, 2, 3"]
key=Hello, value=world
key=F*k, value=me