Home > Backend Development > Golang > How to Efficiently Group and Sum a Slice of Structs in Go?

How to Efficiently Group and Sum a Slice of Structs in Go?

Linda Hamilton
Release: 2024-11-05 07:25:02
Original
726 people have browsed it

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template