3.7 rust 静态块

Cargo.toml

[dependencies]
lazy_static = "1.4.0"

main.rs

#[macro_use]
extern crate lazy_static;
use std::collections::HashMap;

lazy_static! {
    static ref HASHMAP: HashMap<u32, &'static str> = {
        let mut m = HashMap::new();
        m.insert(0, "foo");
        m.insert(1, "bar");
        m.insert(2, "baz");
        m
    };
    static ref COUNT: usize = HASHMAP.len();
    static ref NUMBER: u32 = times_two(21);
}

fn times_two(n: u32) -> u32 { n * 2 }

pub fn test() {
    println!("The map has {} entries.", *COUNT);
    println!("The entry for `0` is "{}".", HASHMAP.get(&0).unwrap());
    println!("A expensive calculation on a static results in: {}.", *NUMBER);
}

注意代码static前有一个单引号,只有一个单引号,没有成对;并不是写错了,而是rust的语法就是如此,运行上面代码输出

The map has 3 entries.
The entry for `0` is "foo".
A expensive calculation on a static results in: 42.
原文地址:https://www.cnblogs.com/perfei/p/14484475.html