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.

RustConfig Management

Code

snippet
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

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:`.