| Crates.io | qsinglton |
| lib.rs | qsinglton |
| version | 0.2.0 |
| created_at | 2025-07-19 06:24:29.572324+00 |
| updated_at | 2025-07-19 06:31:23.70885+00 |
| description | Helper macros to generate singleton definitions |
| homepage | |
| repository | https://github.com/qyuzh/qsinglton |
| max_upload_size | |
| id | 1759965 |
| size | 10,732 |
A Rust procedural macro library for implementing thread-safe singleton patterns with minimal boilerplate.
std::sync::OnceLock for safe concurrent access&'static Self or Arc<Self>init() and global()Add this to your Cargo.toml:
[dependencies]
qsinglton = "0.1.0"
&'static Self)use qsinglton::singleton;
#[singleton]
struct Config {
name: String,
version: String,
}
fn main() {
// Initialize the singleton
Config::init(Config {
name: "MyApp".to_string(),
version: "1.0.0".to_string(),
});
// Access the global instance
let config = Config::global();
println!("App: {} v{}", config.name, config.version);
}
&'static Arc<Self>)use qsinglton::singleton;
#[singleton(arc)]
struct Database {
connection_string: String,
pool_size: usize,
}
fn main() {
// Initialize the singleton
Database::init(Database {
connection_string: "postgresql://localhost/mydb".to_string(),
pool_size: 10,
});
// Access the global instance (can be cloned and moved)
let db = Database::global();
let db_clone = db.clone();
std::thread::spawn(move || {
println!("In thread: {}", db_clone.connection_string);
}).join().unwrap();
}
init(instance: Self)Initializes the singleton with the provided instance. Panics if called more than once.
global() -> &'static Self or global() -> &'static Arc<Self>Returns a reference to the global singleton instance. Panics if called before init().
All generated code is thread-safe and uses std::sync::OnceLock internally to ensure:
This project is licensed under the MIT License - see the LICENSE file for details.