rusthashmap

Idiomatic way to create a constant HashMap with values in Rust


I want to know what is the idiomatic way to create a constant Hashmap with values in Rust?

I have an implementation like:

const LOOKUP_TABLE: HashMap<usize, f64> = HashMap::from([
    (1, 1.1),   // Values are randomly put
    (2, 2.2),
]);

and I get an error:

error[E0015]: cannot call non-const fn `<HashMap<usize, f64> as From<[(usize, f64); 12]>>::from` in constants
  --> 
   |
18 |   const LOOKUP_TABLE: HashMap<usize, f64> = HashMap::from([
   |  _________________________________________________^
19 | |     (1, 1.1),
20 | |     (2, 2.2),
31 | | ]);
   | |__^
   |
   = note: calls in constants are limited to constant functions, tuple structs and tuple variants

Solution

  • Rust's std::collections::HashMap cannot be used to create a const HashMap directly, because it requires dynamic memory allocation, which is not allowed for const values.

    One possible way is to use the lazy_static crate, which allows you to initialize a static variable lazily at runtime. For example:

    use std::collections::HashMap;
    use lazy_static::lazy_static;
    
    lazy_static! {
        static ref COUNTRIES: HashMap<usize, f64> = {
            let mut m = HashMap::new();
            m.insert(1, 1.1);
            m.insert(2, 2.2);
            m                  // return binding m
        };
    }
    

    Another possible way is to use the phf crate, which allows you to create compile-time static collections. For example:

    use phf::{phf_map};
    
    static COUNTRIES: phf::Map<usize, f64> = phf_map! {
        1 => 1.1,
        2 => 2.2,
    };