Once Lock Lazy Initialization

Initialize shared configuration exactly once on first use with std OnceLock, avoiding locks after setup.

RustConfig Management

Code

rustsnippet
27 lines
use std::sync::OnceLock;

static CONFIG: OnceLock<String> = OnceLock::new();

fn load_config() -> String {
    std::env::var("APP_CONFIG").unwrap_or_else(|_| "default".to_string())
}

pub fn config() -> &'static str {
    CONFIG.get_or_init(load_config)
}

pub fn try_override(value: &str) -> Result<(), &'static str> {
    CONFIG.set(value.to_string()).map_err(|_| "config already initialized")
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn init_is_idempotent() {
        let first = config();
        let second = config();
        assert_eq!(first, second);
    }
}

How the snippet works

The working surface is the functions load_config, config, try_override and init_is_idempotent — everything else is wiring.

Fallible operations return Result, forcing the caller to handle both arms explicitly.

What to watch for

  • Plan for an install step: super:: is a real dependency, resolved by the package manager.
  • Errors travel through Result; if you drop the ? operators while adapting, each call site needs its own match.

Applying it

The main signature reads fn load_config() -> String

Callers only need load_config — everything else stays internal.

Statements that matter

pub fn try_override(value: &str) -> Result<(), &'static str> {
CONFIG.set(value.to_string()).map_err(|_| "config already initialized")
}
pub fn config() -> &'static str {
CONFIG.get_or_init(load_config)
}
fn load_config() -> String {
std::env::var("APP_CONFIG").unwrap_or_else(|_| "default".to_string())
}

Interactive Tools for This Topic

FAQ

How are errors reported?
Each fallible operation returns `Result`; nothing is silently discarded.
Are there third-party dependencies?
`super::` — install it with the package manager before running.