How do I create a global mutable singleton in Rust?
How do I create a global mutable singleton in Rust?
Creating a global mutable singleton in Rust can be challenging due to Rust's strict ownership and concurrency rules. However, there are several approaches to achieve this, each with its own trade-offs. Here are some common methods:
lazy_static! and MutexThe lazy_static! macro allows for the lazy initialization of static variables, and Mutex can be used to ensure thread-safe access to the singleton.
#[macro_use]
extern crate lazy_static;
use std::sync::Mutex;
lazy_static! {
static ref SINGLETON: Mutex<MyStruct> = Mutex::new(MyStruct::new());
}
struct MyStruct {
// fields
}
impl MyStruct {
fn new() -> Self {
MyStruct {
// initialize fields
}
}
fn do_something(&self) {
// method implementation
}
}
fn main() {
let singleton = SINGLETON.lock().unwrap();
singleton.do_something();
}
In this example, SINGLETON is a global instance of MyStruct wrapped in a Mutex to ensure that only one thread can access it at a time. The lazy_static! macro ensures that the singleton is initialized only once.
OnceCellThe OnceCell crate provides a way to initialize a global variable exactly once, which can be useful for creating singletons.
use once_cell::sync::OnceCell;
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.