r/learnrust • • 4d 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

16 comments sorted by

17

u/Excession638 4d ago edited 4d ago

There are two common patterns that can be used to solve this. First, initialize the contents first:

impl Default for Parameters {
    fn default() -> Self {
        let mut parameter = HashMap::new();
        for i in 1..NUM_PARAMETERS {
            parameter.insert(Param::Num(i as u16), 0.0);
        }
        Self { parameter }
    }
}

The second is to create yourself, then modify before returning. This should only be used if you need to call methods on yourself to initialize, and even then it's ugly:

impl Default for Parameters {
    fn default() -> Self {
        let mut this = Self {
            parameter: HashMap::new(),
        };
        for i in 1..NUM_PARAMETERS {
            this.parameter.insert(Param::Num(i as u16), 0.0);
        }
        this
    }
}

And as someone else mentioned, you can also use collect to build in one line:

Self {
    parameter: (1..NUM_PARAMETERS as u16)
        .map(|i| (Param::Num(i), 0.0)).collect(),
}

2

u/dmills_00 4d ago

Thanks, one of those will do it for this.

Got a little over 5,000 default entries (Plus whatever the users add) and there really doesn't seem to be a better way to initialize the thing.

7

u/ern0plus4 4d ago

Maybe it's not the best idea to prepare 5000 items. You should use some lazy solution, e.g. create item only on first change, and provide calculated default when reading unchanged item. You save some memory and initialization.

0

u/dmills_00 4d ago

But then I have to allocate at run time, and that sort of matters when the thing is throwing masses of spinning metal around at speed.

Trust me allocating (and then making sure I touch all the pages) before I start executing the business is just good housekeeping in this sort of code. The real pain point for that was the recursive descent G code parser for evaluating the maths.

This is actually middle layer not the actual motion code that runs the servos, so it matters a little bit less, but pausing is still unwelcome.

I am firmly of the view that when it is maybe 80kB or so and running on a semi modern machine, better to do it in one hit on startup (If you cannot use phc to do it at build time, got some of that going on as well).

A 5000 entry hash map between strings or ints and (f64,bool) is not exactly a massive time sink to build.

2

u/karasawa_jp 4d ago

Since you want to avoid reallocations and pre-allocate everything up front, definitely use HashMap::with_capacity(5000) (or slightly larger to cover user additions) if you go with the for loop approach. That way you avoid multiple reallocations and rehashes while populating it.

(Note: If you use .collect() on a range iterator like the top comment suggested, Rust actually pre-allocates the capacity automatically under the hood using size_hint*.)*

1

u/ern0plus4 4d ago

Yeah, what we're talking about, 5000 entry should not be any performance bottleneck, any solution is okay.

If it's embedded or something, pre-allocated slots is the way, doesn't matter, prepared or not.

3

u/cristi1990an 4d ago

Are you asking this from a performance point of view or simply from a code prettieness point of view?

2

u/dmills_00 4d ago

Just pretty, I can see ugly ways to get there, but I am still tending to think like a C guy, Rust has not yet settled as a mode of thought when programming.

2

u/dmills_00 4d ago

Code formatter has screwed it up, great.

Anyone know if there is a way to edit a post to fix it?

5

u/BlossomingBeelz 4d ago

I think you used Code (single line) when you need Code Block (multiline). You should be able to use the ellipses menu to edit it.

2

u/dmills_00 4d ago

Fixed it, thanks.

1

u/ToTheBatmobileGuy 4d ago

Two questions:

Are these values known at compile time?

Will these values be changed at any time during the life of the program?


These two answers will change whether or not it would be a good idea to write the initialization code in a const compatible manner.

1

u/dmills_00 4d ago

The ones that are known at compile time I have in a set of const perfect hashes that is built at compile time by some macro magic from the phc crate, the big list of stuff is user accessible, and (largely) not just user writable, but the buggers can add to it!

This thing is not aimed at running on an STM32 or such, that is other bits of the system, so I am not too bothered by blowing 80kb or so on one time creation of this thing, it is small beer in terms of the potential size of the rest of the data.

2

u/Beginning-Fruit-1397 4d ago

I struggle to see the problem? Create an empty hashmap, populate it, or call collect on your iterator, wathever, and then create the struct wrapper Parameter{hashmap} and return it

1

u/kodemizer 4d ago

I use the maplit crate for this: https://docs.rs/maplit/

1

u/JoshyOrndorff 9h ago

Why doesn't it work as OP wrote?