简体   繁体   中英

Rust's lazy_static implies objects cannot ever be deleted?

Rust's lazy_static crate enables us to create static objects in Rust:

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
    };
}

but as you see, the HashMap must store static strings as well. Does that mean that everytime I add something to this hashmap, it can never be deleted, since it's static?

Any string that you can reference with a &'static str must live until the program terminates. So yes, the way that you have it set up, you would never be able to delete any of the string data that is put into the HashMap . Moreover, outside of the lazy_static block you will also never be able to add anything to the HashMap . This is because outside the lazy_static block you will only be able to obtain a shared reference to the HashMap , and you cannot perform mutation on a HashMap with only a shared reference (ie, a &HashMap ).

If you want to be able to modify the HashMap , you can do so by wrapping it in a Mutex and using owned strings instead of &'static str :

#[macro_use]
extern crate lazy_static;

use std::collections::HashMap;
use std::sync::Mutex;

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

fn main() {
    println!("{:?}", HASHMAP.lock().unwrap().iter());
    HASHMAP.lock().unwrap().remove(&1);
    println!("{:?}", HASHMAP.lock().unwrap().iter());
}

This gives an output like:

[(0, "foo"), (1, "bar"), (2, "baz")]
[(0, "foo"), (2, "baz")]

However, it might be worth asking whether a static object is really what you need. In Rust, typically it is more idiomatic (and simpler and better performing) to use local variables instead of statics.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM