this post was submitted on 25 Jun 2023
6 points (100.0% liked)

Rust Programming

8163 readers
4 users here now

founded 5 years ago
MODERATORS
 

I want to create a global hash map that maps strings to vectors of colors. This data needs to be queried by multiple functions and should just be hard coded into the program. That doesn't seem possible.

Now, how is the right (tm) way to do something like that in Rust? What if you need just a bunch of data structures from the beginning of the program until its end where some of the data needs to allocated?

top 8 comments
sorted by: hot top controversial new old
[–] PrincipleOfCharity@0v0.social 6 points 1 year ago* (last edited 1 year ago)

Is the hash map immutable? If so, look at the rust-phf crate.

[–] livingcoder@lemmy.austinwadeheller.com 6 points 1 year ago (1 children)
[–] SigmarStern@discuss.tchncs.de 3 points 1 year ago (2 children)

I heard about this, but I wasn't sure it was the right way. Or if Rust developers just straight up avoid situations like this.

[–] Nyefan@lemmy.ml 3 points 1 year ago

lazy_static was the standard way as far as I'm concerned until this month. OnceCell or OnceLock should fill this role now.

[–] livingcoder@lemmy.austinwadeheller.com 2 points 1 year ago* (last edited 1 year ago)

I generally avoid this situation. At best I'll create an Rc<HashMap<T, U>> to pass around. I find that having a need for a static variable can be an indication of bad design. It often makes the code that depends on it untestable.

[–] Hexorg@beehaw.org 5 points 1 year ago (1 children)

Just make a function that matches string and outputs your colors. It’ll be faster and easier than any extra crate.

[–] SigmarStern@discuss.tchncs.de 2 points 1 year ago (1 children)

The thing is, I also want to query all possible colors. And that would then be in a different function so I'd have to change two functions whenever I add a new color and I don't like that.

[–] Hexorg@beehaw.org 2 points 1 year ago

Then make a vector of colors, and make a function that matches string to index in that vector

load more comments
view more: next ›