Global const of HashSet


#1

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?


#2

lazy_static is a popular solution.


#3

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.


#4

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.


#5

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


#6

Thank you for interesting informaion!