Build A Lazy Lookup Table With OnceLock
Initialize a static HashMap once with OnceLock::get_or_init for fast read-only lookups, and reject duplicate writes with OnceLock::set.
Code
use std::collections::HashMap;
use std::sync::OnceLock;
fn service_port(name: &str) -> Option<u16> {
static PORTS: OnceLock<HashMap<&'static str, u16>> = OnceLock::new();
let table = PORTS.get_or_init(|| {
println!("initializing service port table once");
HashMap::from([("auth", 8081), ("billing", 8082), ("search", 8083)])
});
table.get(name).copied()
}
fn main() {
for svc in ["auth", "search", "unknown", "billing"] {
println!("{svc} -> {:?}", service_port(svc));
}
let token: OnceLock<String> = OnceLock::new();
println!("first set ok: {}", token.set("boot-key-1".into()).is_ok());
println!("second set ok: {}", token.set("boot-key-2".into()).is_ok());
println!("stored token: {:?}", token.get());
}Implementation flow — Build A Lazy Lookup Table With OnceLock
The code’s whole job belongs to the functions service_port and main.
One loop does the cycling here: for svc in ["auth", "search", "unknown", "billing"].
What to watch for
- Requires solely a stock language runtime with zero package additions.
Putting it to use
The entry-point signature is fn service_port(name: &str) -> Option<u16>
The demo output is labeled (initializing service port table once, first set ok:, second set ok:); each label names the call that printed it.
main calls 1 helper in sequence: service_port.
Core lines
static PORTS: OnceLock<HashMap<&'static str, u16>> = OnceLock::new();
Interactive Tools for This Topic
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.JSON to YAML ConverterConvert JSON to readable YAML with nested block mappings, sequences, and quoting only where it is required.
FAQ
- What does Build A Lazy Lookup Table With OnceLock print when run?
- Execute the whole file; each printed line is prefixed with a label like `initializing service port table once`, `first set ok:`, `second set ok:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.