Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Singleton #226

Open
Tracked by #116
simonsan opened this issue Feb 22, 2021 · 1 comment
Open
Tracked by #116

Singleton #226

simonsan opened this issue Feb 22, 2021 · 1 comment
Labels
A-pattern Area: Content about Patterns C-addition Category: Adding new content, something that didn't exist in the repository before C-needs discussion Area: Something that is not clear to everyone if it fixes something/adds valuable content

Comments

@simonsan
Copy link
Collaborator

Tracking issue for merging: https://github.com/lpxxn/rust-design-pattern/blob/master/creational/singleton.rs

Example:

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())
}
@simonsan simonsan added C-addition Category: Adding new content, something that didn't exist in the repository before A-pattern Area: Content about Patterns labels Feb 22, 2021
@simonsan
Copy link
Collaborator Author

Tracking discussion on merging: lpxxn/rust-design-pattern#7

@simonsan simonsan added the C-needs discussion Area: Something that is not clear to everyone if it fixes something/adds valuable content label Feb 23, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
A-pattern Area: Content about Patterns C-addition Category: Adding new content, something that didn't exist in the repository before C-needs discussion Area: Something that is not clear to everyone if it fixes something/adds valuable content
Projects
None yet
Development

No branches or pull requests

1 participant