Home > Article > Backend Development > How to Efficiently Group and Sum a Slice of Structs in Go?
Grouping and Summing a Slice of Structs in Go
In this scenario, you aim to group a slice of structs based on eight specific fields and sum an additional integer field, similar to SQL queries. To achieve this, you initially considered creating an Equal function for comparing structs and iteratively checking if each item is in a hash table, adding or summing the field accordingly.
While your approach is valid, there's an alternative solution that offers efficiency and simplicity. Refactor your types so that the key fields (id1-id8) form a separate struct, Key. This allows you to use Key as a map key, since structs are comparable in Go.
Here's the modified type definition:
<code class="go">type Key struct { id1 int id2 int id3 int id4 int id5 int id6 int id7 int id8 int } type Register struct { key Key money int }</code>
To group and calculate the sum, employ a map[Key]int. Use Register.key as the map key to collect all registers with the same keys (ids):
<code class="go">regs := []*Register{ {Key{id1: 345}, 1500}, {Key{id1: 345, id2: 140}, 2700}, {Key{id1: 345, id2: 140}, 1300}, {Key{id1: 345}, 1000}, {Key{id3: 999}, 1000}, {Key{id3: 999}, 2000}, } // calculate sum: m := map[Key]int{} for _, v := range regs { m[v.key] += v.money }</code>
This solution provides a straightforward and efficient way to group and sum the provided slice of structs. No additional libraries or complex iterating mechanisms are necessary.
The above is the detailed content of How to Efficiently Group and Sum a Slice of Structs in Go?. For more information, please follow other related articles on the PHP Chinese website!