How do I create a empty dictionary as a global variable?

Hi

How do I create a empty dictionary as a global variable in Rust and then append key value pairs to this empty global variable in the main function.
Also what is data type for an dictionary/empty dictionary.

Thanks
Spencer

Generally mutable global variables are strongly discouraged in Rust. If you need a single-time initialization and no modification after that, you can use lazy_static. The type for dictionaries is HashMap.

1 Like

Ok how do I create a empty dictionary using lazy static and then append to it from main?

You create a lazy static like this:

lazy_static! {
    static ref HASHMAP: HashMap<u32, &'static str> = {
        let mut m = HashMap::new();
        m.insert(0, "foo");
        m.insert(1, "bar");
        m.insert(2, "baz");
        m
    };
}

You cannot append to it from main, as it is not mutable outside the block above.

I need to be able to append to in main. How do I do this. Because this is a global variable with empty dictionary.

You'll need to wrap it in synchronization of some sort, like a Mutex or RwLock.

use std::{collections::HashMap, sync::Mutex};

lazy_static! {
    static ref HASHMAP: Mutex<HashMap<u32, &'static str>> = Mutex::new(HashMap::new());
}

fn main() {
    // Lock the mutex so we can safely update the hashmap.
    let mut hashmap = HASHMAP.lock().unwrap();
    hashmap.insert(1, "foo");
}
2 Likes