capypad
0 day streak
rust / intermediate
Snippet

Lazy Initialization with OnceLock

OnceLock provides thread-safe lazy initialization for static data. The configuration is only read from disk when first accessed, not at program startup. This improves startup time if the config is never needed and ensures expensive operations are not repeated. Unlike lazy_static, OnceLock is built into the standard library since Rust 1.70 and has no macro overhead. The get_or_init method guarantees the closure runs exactly once, even with concurrent access.

snippet.rs
rust
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
use std::sync::OnceLock;
use std::fs;
 
static CONFIG: OnceLock<Config> = OnceLock::new();
 
struct Config {
app_name: String,
max_connections: u32,
debug_mode: bool,
}
 
fn get_config() -> &'static Config {
CONFIG.get_or_init(|| {
let contents = fs::read_to_string("config.txt").unwrap_or_default();
Config {
app_name: contents.lines().next().unwrap_or("Default").to_string(),
max_connections: 100,
debug_mode: true,
}
})
}
 
fn main() {
let config = get_config();
println!("App: {}, Connections: {}", config.app_name, config.max_connections);
}
Breakdown
1
static CONFIG: OnceLock<Config> = OnceLock::new()
Static OnceLock—initialized once, never changed, shared across all threads
2
CONFIG.get_or_init(|| {...})
Returns existing value or initializes atomically on first call