6

How can I create a immutable, globally accessible HashSet that stores values known at compile time? I know global state is unwanted, but since it's immutable it might still be acceptable, right?

static global_set: HashSet<String> = create_set();

fn create_set() -> HashSet<String> {
    let mut new_set: HashSet<String> = HashSet::new();

    new_set.insert("ONE".to_string());
    new_set.insert("TWO".to_string());
    new_set.insert("THREE".to_string());

    new_set
}

This does not work.

error[E0015]: calls in statics are limited to constant functions, tuple structs and tuple variants
  --> src\lib.rs:62:38
   |
62 | static cclass_map: HashSet<String> = populate_hashmap();
   |                                      ^^^^^^^^^^^^^^^^^^

If I make the create_set a const fn it complains that the mutable references in const fn are unstable

I feel there must be a better way to do this. How can it be done in a better way? Or how can I get this to work?

mottosson
  • 3,283
  • 4
  • 35
  • 73

0 Answers0