Rust lazy_static!
示例
使用lazy_static板条箱创建在运行时初始化的全局不可变变量。我们HashMap用作示范。
在Cargo.toml:
[dependencies] lazy_static = "0.1.*"
在main.rs:
#[macro_use]
extern crate lazy_static;
lazy_static! {
static ref HASHMAP: HashMap<u32, &'static str> = {
let mut m = HashMap::new();
m.insert(0, "hello");
m.insert(1, ",");
m.insert(2, " ");
m.insert(3, "world");
m
};
static ref COUNT: usize = HASHMAP.len();
}
fn main() {
// We dereference COUNT because it's type is &usize
println!("The map has {} entries.", *COUNT);
//在这里,由于Deref强制,我们不使用*取消引用
println!("The entry for `0` is \"{}\".", HASHMAP.get(&0).unwrap());
}
热门推荐
6 保研的祝福语简短
10 年轻20岁祝福语简短
11 朋友结婚祝福语信息简短
12 女孩婚礼贺卡祝福语简短
13 30段点歌简短祝福语
14 虎年春节祝福语图文简短
15 写给后妈祝福语大全简短
16 简短回复生日祝福语
17 校长送毕业祝福语简短
18 毕业立体贺卡祝福语简短