Is there a way to create a constant map in Rust?


#1

I’m assuming the answer is “No”, because it seems like you can’t do any allocation to set up a constant. What’s the best way to do this/approximate this? I was thinking something super ugly like creating a struct that has a get_map_const() function that returns the ‘constant’ value. Is there a cleaner alternative?

(Note that I can’t avoid the need for a map constant - but I can come up with different representations for it.)


#2

You mean, a static HashMap? No, it isn’t possible, because Rust does not (yet) support compile-time evaluation of code of such complexity as would be needed to implement a hashmap.

What are you trying to do that requires a static hashmap?

Edit: Actually, you might want to look into something like this: https://crates.io/crates/phf


#3

Ah. I figured. And no - haven’t taken a look at phf; will look tonight. As for what I’m writing: it’s a code-generator to a spec, and the spec defines map literals that have to be translated to the target language.


#4

Sounds like a PHF would be a perfect fit for that.


#5

You can also use the lazy_static crate for this.


#6

What about just a function with a single match statement? Would that fit your use case?


#7

Thanks guys - I’ll take a look at these options.