Once Lock Lazy Initialization
Initialize shared configuration exactly once on first use with std OnceLock, avoiding locks after setup.
Code
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);
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.