-1

I have the struct that looks like:

pub struct MonthlyProjection {
    pub sequence: u32,
    pub total_deposit: f64,
}

I have this function which takes reference of the vector that contains these structs:

fn generate_projections(simulation_results: &Vec<MonthlySimulationResult>)

Inside this function, I have to group the MonthlyProject structs by their sequences, and do some calculation with it.

So here is my logic:

  1. Create mutable HashMap<u32, Vec<MonthlySimulationResult>>, called result_map
  2. For loop over the simulation_results vector
  3. If the result_map already has the vector for the given sequence number, then insert the item into that existing vector, then update the result_map
  4. If the result_map does not have the existing vector for the given sequence number, then create new vector, insert the struct, and update the result_map

How would you do this?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
user8079
  • 163
  • 1
  • 9
  • Have a look at the `entry` method on `HashMap`: https://doc.rust-lang.org/std/collections/hash_map/struct.HashMap.html#method.entry – Rocoty Mar 27 '20 at 08:05

1 Answers1

1

If you don't mind pulling in the extra dependency, maybe look at itertools:

https://docs.rs/itertools/0.9.0/itertools/trait.Itertools.html#method.group_by

Otherwise, you can write a for-loop using the entry API:

let mut result_map: HashMap<u32, Vec<_>> = HashMap::new();
for projection in simulation_results {
    result_map.entry(projection.sequence).or_default().push(projection);
}
result_map

(Playground.)

Note that you specified a MonthlyProjection type but then you specified the function header and its return type with MonthlySimulationResult, so not clear what's going on there. Also, you pass in a reference to the Vec<MonthlyProjection> but return a transitively owned MonthlySimulationResult, so you need to do something there.

djc
  • 11,603
  • 5
  • 41
  • 54