patternrustMajor
Rust best practices when specifying a constant hash map
Viewed 0 times
constantpracticesbestwhenrusthashspecifyingmap
Problem
I'm trying to set a constant, predefined hash map in Rust. I'm not sure what the best practice is in Rust for this.
These will then be referenced later in the library.
If this is bad, I'm guessing a match in a function is the best way?
use std::collections::HashMap;
pub const Countries: HashMap = [
("UK", "United Kingdom"),
("US", "United States")
].iter().cloned().collect();These will then be referenced later in the library.
If this is bad, I'm guessing a match in a function is the best way?
Solution
You can use https://crates.io/crates/lazy_static (lazily executed at runtime).
I personally use https://crates.io/crates/phf (compile-time static collections) for this if the data is truly static.
I personally use https://crates.io/crates/phf (compile-time static collections) for this if the data is truly static.
use phf::phf_map;
static COUNTRIES: phf::Map = phf_map! {
"US" => "United States",
"UK" => "United Kingdom",
};
Context
Stack Overflow Q#60273064, score: 79
Revisions (0)
No revisions yet.