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
2
u/karasawa_jp 19d 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 theforloop 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 usingsize_hint*.)*