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.
Code
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
Box Shadow GeneratorBuild CSS box-shadow values with offset, blur, spread, color, opacity, and inset controls, with a live preview of the result.Dotenv File ParserParse .env file content into a JSON object, handling comments, export prefixes, single quotes, and double-quoted escape sequences.INI File ParserParse INI configuration files into nested JSON with section objects, global keys, and both semicolon and hash comment support.JSON to TOML ConverterTurn a JSON object into TOML, emitting nested objects as tables and arrays of objects as array-of-tables blocks.
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:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.