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);
}
}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 ownmatch.
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
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
- 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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.