rust 10 lines · 1 tab

once_cell for lazy static initialization

Marcus Chen Jan 2026
1 tab
use once_cell::sync::Lazy;
use regex::Regex;

static EMAIL_REGEX: Lazy<Regex> = Lazy::new(|| {
    Regex::new(r"^[^ @]+@[^ @]+.[^ @]+$").unwrap()
});

fn is_valid_email(email: &str) -> bool {
    EMAIL_REGEX.is_match(email)
}
1 file · rust Explain with highlit

once_cell provides Lazy and OnceCell for safe lazy initialization. Unlike lazy_static!, it doesn't require macros. Lazy<T> is initialized on first access via a closure. I use it for config, regex patterns, or expensive-to-create globals. OnceCell is similar but initialized explicitly, useful for runtime-determined values. Both are thread-safe and lock-free after initialization. The standard library added OnceLock in Rust 1.70, but once_cell still has a richer API and works on older Rust versions. Lazy initialization defers costs until needed and can improve startup time. It's especially useful in libraries where you don't control initialization order.


Related snips

Share this code

Here's the card — post it anywhere.

once_cell for lazy static initialization — share card
Link copied