Rust design patterns

rust design patterns

1 Like

Careful, this is unsound (more generally, static mut is actually an anti-pattern in Rust). The crate ::once_cell was created to do this very pattern in a sound manner:

fn get_config () -> &'static Mutex<Config>
    use ::once_cell::Sync::OnceCell;

    static CONF: OnceCell<Mutex<Config>> = OnceCell::new();

    CONF.get_or_init(|| {
        println!("init"); // do once
        Mutex::new(Config {
            db_connection_str: "test config".to_string(),

To expand on this, it's unsound because it allows for a data race between two competing threads on first access, and it creates overlapping unique references when called from multiple threads, regardless of when it is called. Both of these are UB.


This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.