Construct a Rust function that uses lazy_static or OnceLock (std) to create a…
- User
Construct a Rust function that uses
lazy_staticorOnceLock(std) to create a thread-safe global singleton. Assistant
Construct a Rust function that uses lazy_static or OnceLock (std) to create a thread-safe global singleton.
The user wants a Rust function that creates a thread-safe global singleton.
They specifically mentioned using lazy_static or OnceLock (which is in the standard library since Rust 1.70).
I should provide examples for both approaches to give a complete answer.
Approach 1: std::sync::OnceLock (Modern, Standard Library)
static NAME: OnceLock<Type> = OnceLock::new();NAME.get_or_init(|| { initialization_logic }).Approach 2: lazy_static (Legacy/Popular Crate)
lazy_static to Cargo.toml.lazy_static! { static ref NAME: Type = initialization_logic; }NAME.some_method(). Note that dereferencing requires thread-safe handling, usually handled by the crate returning a smart pointer-like wrapper.Scenario: I need a concrete example. A "Configuration" or "Database Pool" is the standard use case for singletons. Let's stick to a simple configuration struct to keep it readable.
Step 1: The OnceLock Example
Config.Step 2: The lazy_static Example
Comparison/Advice:
OnceLock for new projects (no deps).lazy_static is still useful for complex initialization logic or older codebases, or if OnceLock's initialization closure isn't flexible enough (though it usually is). Correction: once_cell (the crate OnceLock came from) has Lazy which is more ergonomic than OnceLock for statics (auto-initializes). lazy_static is basically the macro version of Lazy.std::sync::LazyLock is coming soon (or in nightly/beta), but the prompt specifically asked for OnceLock or lazy_static. I will stick to OnceLock as requested, but maybe mention LazyLock as a side note for "truly lazy" syntax without the get_or_init boilerplate.Refining the OnceLock code:
use std::sync::OnceLock;
pub struct Singleton {
pub data: String,
}
impl Singleton {
fn global() -> &'static Singleton {
static INSTANCE: OnceLock<Singleton> = OnceLock::new();
INSTANCE.get_or_init(|| Singleton {
data: String::from("Initialized"),
})
}
}
Refining the lazy_static code:
use lazy_static::lazy_static;
use std::sync::Mutex;
// lazy_static usually implies interior mutability if we want to change data,
// or just immutable data. Let's stick to immutable for simplicity, or Mutex for realism.
// Actually, a read-only singleton is simpler. Let's do a read-only Config.
pub struct Config { ... }
lazy_static! {
static ref CONFIG: Config = Config::new();
}
Thread Safety:
Both are thread-safe. OnceLock guarantees atomic initialization. lazy_static does the same.
Structure of the Answer:
std::sync::OnceLock if on Rust 1.70+ (no dependencies).OnceLock): Complete, runnable example.lazy_static): Complete, runnable example with dependency note.Drafting the OnceLock function:
I need a function that uses the singleton.
fn do_something() { let val = MY_SINGLETON.get_or_init(...); ... }
Let's create a get_global_instance() function.
Wait, there's LazyLock in 1.80 (very recent).
Since LazyLock is extremely new (stabilized in 1.80), most people asking this likely have 1.70+ but maybe not 1.80+. OnceLock is the safe bet for the standard library request right now.
Refining the OnceLock example:
The user asked for a "function that uses... to create...".
So the function should probably be the accessor.
use std::sync::OnceLock;
struct Database {
connection_string: String,
}
static DB: OnceLock<Database> = OnceLock::new();
pub fn get_database() -> &'static Database {
DB.get_or_init(|| {
// Expensive initialization happens here exactly once
println!("Initializing database...");
Database {
connection_string: "postgres://...".to_string(),
}
})
}
This looks solid.
Refining the lazy_static example:
use lazy_static::lazy_static;
struct Database {
connection_string: String,
}
lazy_static! {
static ref DB: Database = {
println!("Initializing database...");
Database {
connection_string: "postgres://...".to_string(),
}
};
}
pub fn get_database() -> &'static Database {
&*DB // or just &DB if deref coercion works, but explicit is clearer
}
Final Polish: Ensure code compiles. Explain why it is thread-safe (happens-before relationship during initialization).
Let's write the final response.
Here are examples of how to achieve this using both the standard library (std::sync::OnceLock, available since Rust 1.70) and the popular external crate lazy_static.
std::sync::OnceLockIf you are using Rust 1.70 or newer, prefer this method. It is part of the standard library, requires no external dependencies, and offers a cleaner API.
We define a static variable wrapped in OnceLock. We then create a function (often named instance() or global()) that attempts to return a reference to the data. If the data doesn't exist yet, it initializes it atomically.
use std::sync::OnceLock;
use std::time::Instant;
// 1. Define your struct
struct Configuration {
pub app_name: String,
pub start_time: Instant,
}
// 2. Define the static global variable
static GLOBAL_CONFIG: OnceLock<Configuration> = OnceLock::new();
// 3. Define the accessor function
pub fn get_config() -> &'static Configuration {
// get_or_init ensures this closure runs exactly once,
// even if multiple threads call this simultaneously.
GLOBAL_CONFIG.get_or_init(|| {
// Simulate expensive setup
println!("Initializing singleton...");
Configuration {
app_name: String::from("My Super App"),
start_time: Instant::now(),
}
})
}
fn main() {
// First call: triggers initialization
let config = get_config();
println!("App: {}", config.app_name);
// Subsequent calls: returns existing reference (fast)
let config2 = get_config();
// Prove it's the same instance by checking memory addresses
assert!(std::ptr::eq(config, config2));
println!("Singleton verified!");
}
lazy_staticIf you are on an older version of Rust or prefer the macro syntax, you can use the lazy_static crate.
Add this to your dependencies:
[dependencies]
lazy_static = "1.4"
use lazy_static::lazy_static;
use std::sync::Mutex; // Used here to allow modification, purely as an example
// Define a struct
struct DatabasePool {
connections: u32,
}
// Use the macro to define the static
lazy_static! {
// Note: lazy_static requires the type to be thread-safe.
// If you need mutable state, wrap it in a Mutex or RwLock.
static ref DB_POOL: Mutex<DatabasePool> = Mutex::new(DatabasePool {
connections: 0,
});
}
// A function to access the singleton
pub fn get_db_instance() -> &'static Mutex<DatabasePool> {
// On first access, the code inside lazy_static! runs once.
// Subsequent accesses return the static reference immediately.
&DB_POOL
}
fn main() {
// Access the singleton
let db = get_db_instance();
// We can mutate it because we used a Mutex
let mut pool = db.lock().unwrap();
pool.connections += 1;
println!("Connections: {}", pool.connections);
}
| Feature | std::sync::OnceLock | lazy_static |
|---|---|---|
| Installation | Built-in (Std Library) | Requires cargo add lazy_static |
| Mutability | Immutable by default (combine with RwLock for mutation) | Immutable by default (combine with Mutex for mutation) |
| Syntax | Standard generic methods | Macro-based |
| Initialization | Lazy (happens on first get_or_init) | Lazy (happens on first access) |
OnceLock for Singletons?|| { ... }) is executed only once, even if two threads call get_config() at the exact same nanosecond.OnceLock is very fast (basically an atomic check).OnceLock handles poisoning (if the initialization panics, other threads can attempt to initialize it again).