src/main.rs:
xxxxxxxxxx
use std::{mem::MaybeUninit, sync::Once};
struct MyStruct {
field: String,
}
impl MyStruct {
fn get_instance() -> &'static mut Self {
static mut MY_STRUCT_INSTANCE: MaybeUninit<MyStruct> = MaybeUninit::uninit();
static ONCE: Once = Once::new();
ONCE.call_once(|| unsafe {
MY_STRUCT_INSTANCE.as_mut_ptr().write(MyStruct {
field: "my struct".to_string(),
})
});
unsafe { &mut *(MY_STRUCT_INSTANCE.as_mut_ptr()) }
}
}
fn main() {
let config1 = MyStruct::get_instance();
let config2 = MyStruct::get_instance();
assert_eq!(config1.field, config2.field);
config2.field = "my struct 2".to_string();
assert_eq!(config1.field, config2.field);
}