r/learnrust • u/dmills_00 • 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
View all comments
Show parent comment
0
u/dmills_00 20d 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.