Global static

RecipeCratesCategories
Declare lazily evaluated constantlazy_staticcat-caching cat-rust-patterns cat-memory-management

Declare lazily evaluated constant

lazy_static lazy_static-crates.io lazy_static-github lazy_static-lib.rs cat-caching cat-rust-patterns cat-memory-management

Declares a lazily evaluated constant std::collections::HashMap⮳. The std::collections::HashMap⮳ will be evaluated once and stored behind a global static reference.

use std::collections::HashMap;

use lazy_static::lazy_static;

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");
}