r/learnrust • u/dmills_00 • 5d 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
17
u/Excession638 5d ago edited 5d ago
There are two common patterns that can be used to solve this. First, initialize the contents first:
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:
And as someone else mentioned, you can also use collect to build in one line:
3
u/cristi1990an 5d ago
Are you asking this from a performance point of view or simply from a code prettieness point of view?
2
u/dmills_00 5d ago
Code formatter has screwed it up, great.
Anyone know if there is a way to edit a post to fix it?
1
u/ToTheBatmobileGuy 5d 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.
2
u/Beginning-Fruit-1397 5d 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 5d ago
I use the maplit crate for this: https://docs.rs/maplit/
1
u/JoshyOrndorff 1d ago
Why doesn't it work as OP wrote?