forked from lpxxn/rust-design-pattern
-
Notifications
You must be signed in to change notification settings - Fork 0
/
singleton.rs
36 lines (29 loc) · 819 Bytes
/
singleton.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
use std::mem::MaybeUninit;
use std::sync::{Mutex, Once};
#[derive(Debug)]
struct Config {
db_connection_str: String,
}
fn get_config() -> &'static Mutex<Config> {
static mut CONF: MaybeUninit<Mutex<Config>> = MaybeUninit::uninit();
static ONCE: Once = Once::new();
ONCE.call_once(|| unsafe {
CONF.as_mut_ptr().write(Mutex::new(Config {
db_connection_str: "test config".to_string(),
}));
});
unsafe { &*CONF.as_ptr() }
}
fn main() {
let f1 = get_config();
println!("{:?}", f1);
// modify
{
let mut conf = f1.lock().unwrap();
conf.db_connection_str = "hello".to_string();
}
let f2 = get_config();
println!("{:?}", f2);
let conf2 = f2.lock().unwrap();
assert_eq!(conf2.db_connection_str, "hello".to_string())
}