Box Leak Static Lookup Table

Promote a one-shot heap map to a program-lifetime static table with Box::leak, trading an allocation for read-only global lookup without cloning.

RustConfig Management

Code

rustsnippet
21 lines
use std::collections::HashMap;

fn main() {
    let mut region_names: HashMap<&str, &str> = HashMap::new();
    region_names.insert("us-east", "N. Virginia");
    region_names.insert("eu-west", "Ireland");
    region_names.insert("ap-south", "Mumbai");

    // static lookup table: Box::leak 把堆上 HashMap 提升为 'static,进程生命周期内不释放
    // 适合构建一次、全程序只读的查表;代价是内存直到进程结束才归还
    let table: &'static HashMap<&str, &str> = Box::leak(Box::new(region_names));

    for region in ["us-east", "ap-south", "cn-north"] {
        match table.get(region) {
            Some(name) => println!("{} -> {}", region, name),
            None => println!("{} -> unknown region", region),
        }
    }

    println!("table size: {}", table.len());
}

How it works

Structurally, expect the function main and nothing else.

The one repetition in this snippet is the loop for region in ["us-east", "ap-south", "cn-north"]. A match enumerates the value’s possible shapes, and the compiler rejects any arm you forget.

Caveats

  • Every symbol it touches is a language built-in — nothing to fetch.

Using it

Signature: fn main()

The run emits 1 labeled section — table size: — one per step.

Key statements

match table.get(region) {
Some(name) => println!("{} -> {}", region, name),
None => println!("{} -> unknown region", region),
}

Interactive Tools for This Topic

FAQ

What does Box Leak Static Lookup Table print when run?
Execute the whole file; each printed line is prefixed with a label like `table size:`.