Grouping and Summing Slices of Structs in Go
When analyzing data, it is often necessary to group similar elements together and calculate aggregate values for each group. In LINQ, this can be achieved efficiently using in-memory queries. Go provides a versatile way to perform similar operations using maps and closures.
Consider a slice of Register structs, where each struct contains multiple unique identifiers (id1 to id8) and an integer value (money). The goal is to group these registers by their unique identifiers and sum the corresponding money values for each group.
Manual Grouping and Summing:
One approach is to create a custom Equal function to compare Register structs based on their identifiers. Then, iterate over the slice, checking if each register is already present in a hash table. If it is, the money value is incremented. If it is not, a new entry is added to the hash table containing the Register and an initial money value of 0.
Using a Key Struct and Map:
Go's maps provide a more efficient way to perform grouping and summing operations. By defining a separate Key struct that contains only the unique identifiers (id1 to id8), you can use it as a unique key for a map. The values in the map can be the sum of money values for registers with the same identifier combination.
To implement this approach:
<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>
<code class="go">m := map[Key]int{}</code>
<code class="go">for _, v := range regs { m[v.key] += v.money }</code>
Output and Formatting:
To display the results nicely, you can format the Key struct with all its fields prefixed with id. For example:
<code class="go">fmt.Println("Nice output:") for k, v := range m { fmt.Printf("%+3v: %d\n", k, v) }</code>
Conclusion:
Using maps with key structs is an efficient and flexible way to group and sum slices of structs in Go. It provides a performant alternative to manual grouping and summation, especially when dealing with large datasets.
The above is the detailed content of How can I group and sum slices of structs in Go using maps and key structs?. For more information, please follow other related articles on the PHP Chinese website!