44

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.

use std::collections::HashMap;

pub const Countries: HashMap<&str, &str> = [
    ("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?

joedborg
  • 17,651
  • 32
  • 84
  • 118
  • i used something similar lately (together with [`lazy_static`](https://docs.rs/lazy_static/1.2.0/lazy_static/); there is even a `HashMap` example in the doc). interested to see what people will suggest here. – hiro protagonist Feb 18 '20 at 06:26

1 Answers1

58

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.

use phf::{phf_map};

static COUNTRIES: phf::Map<&'static str, &'static str> = phf_map! {
    "US" => "United States",
    "UK" => "United Kingdom",
};
Martin Gallagher
  • 4,444
  • 2
  • 28
  • 26