forked from lpxxn/rust-design-pattern
-
Notifications
You must be signed in to change notification settings - Fork 0
/
singleton.rs
35 lines (30 loc) · 782 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
use std::sync::{Arc, Mutex};
#[derive(Debug)]
struct Config {
db_connection_str: String,
}
fn get_config() -> Arc<Mutex<Config>> {
static mut CONF: Option<Arc<Mutex<Config>>> = None;
unsafe {
CONF.get_or_insert_with(|| {
println!("init"); // do once
Arc::new(Mutex::new(Config {
db_connection_str: "test config".to_string(),
}))
})
.clone()
}
}
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())
}