1. 常量
需要安装lazy_static
库,可通过cargo add lazy_static
命令安装
[dependencies] lazy_static = "1.4.0"
|
1.1 声明延迟计算常量
声明延迟计算的常量 HashMap
。HashMap
将被计算一次,随后存储在全局静态(全局堆栈)引用。
use lazy_static::lazy_static; use std::collections::HashMap;
lazy_static! { static ref PRIVILEGES: HashMap<&'static str, Vec<&'static str>> = { let mut map = HashMap::new(); map.insert("James", vec!["user", "admin"]); map.insert("Jim", vec!["user"]); map }; }
fn show_access(name: &str) { let access = PRIVILEGES.get(name); println!("{}: {:?}", name, access); }
fn main() { let access = PRIVILEGES.get("James"); println!("James: {:?}", access);
show_access("Jim"); }
|
James: Some(["user", "admin"]) Jim: Some(["user"])
|