Initialization of global static variables is a simple and natural thing to do in his programming language, but not so easy in Rust. If a global static variable is defined as follows, an error is reported:

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

Static variables do not allow dynamic memory allocation:

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)Copy the code

Lazy_static provides a way to initialize static global variables, which are deferred until the first call and initialized only once through the lazy_static macro. The lazy_static macro, which matches static ref, defines static variables as immutable references. Such as:

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); })}Copy the code

Output:

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