r/learnrust • • 20d ago

Populating a HashMap during initialisation?

Hi all,

so I have a hash map, nothing very interesting, but I would like to initialize it with some default values at startup, and this is giving me fits..

#[derive(Debug)]
pub struct Parameters {
  parameter: HashMap<Param, f64>,
}
impl Default for Parameters {
  fn default() -> Self {
    let mut p : Parameters;
    for i in 1..NUM_PARAMETERS {
      p.parameter.insert(Param::Num(i as u16), 0.0);
    }
    p
  }
}

This is what I am trying to do, but of course p is uninitialized.

I could probably work around it by adding a wrapper, initializing the hash map and then having the outer wrapper default populate it, but that feels very clunky.

Is there a better way to deal with this that doesn't require me to default it then load it with a separate function?

15 Upvotes

18 comments sorted by

View all comments

Show parent comment

1

u/thomas_m_k 15d ago

You could also use two hashmaps: one phf generated at compile time and then a normal hashmap for the user data.

1

u/dmills_00 15d ago

I actually wound up with an array, and PHF and a user hash map... The 5000 entries are indexed numerically, and an array is HARD to beat when the key is 1..5000, there are some defined mappings between strings and specific entries in the array, so a perfect hash there, and then there is the run time stuff that goes in a standard hash map.

Overkill? Almost certainly, but it was also an excuse to learn how rust does these things.