Global const of HashSet

I need global const or static variable of HashSet. (Actually not HashSet but Array of HashSet).

const foo: HashSet<usize> = vec![0, 1, 2].into_iter().collect();

The above code outputs two kinds of errors.
"constants are not allowed to have destructors"
"method calls in constants are limited to constant inherent methods"

How can I avoid these errors?

lazy_static is a popular solution.


Thank you!
I l tried and it works well!

I have a naive question.
Why does Rust prohibit it even though it can avoid by macro?
I think that It just raises learning cost.

The problem is that :

  • const value are evaluated at compile time and vec![0, 1, 2].into_iter().collect() can't be evaluated at compile time in Rust yet
  • statics can't be initialised before the program start (might rise safety issues).

lazy_static solve this by initialising the value on first use.


phf with phf_codegen may also be interesting. It can be used to generate actual static sets and maps through a build script.


Thank you for interesting informaion!