iTranslated by AI
The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🐭
[Go] How to count elements in a slice of structs by field
As stated in the title.
I've written about "1. Using a struct" and "2. Using a map".
Personally, I find the struct approach easier to handle and prefer it.
I have implemented an example to aggregate a group of people by blood type.
1. Using a struct
We create a counter and simply increment it.
// You can edit this code!
// Click here and start typing.
package main
import (
"fmt"
"math/rand"
"time"
)
type Person struct {
Id int
BloodType string
}
type Persons []Person
func generateDummys(size int) Persons {
rand.Seed(time.Now().UnixNano())
ps := make(Persons, 0, size)
for i := 0; i < size; i++ {
var p Person
p.Id = i
rd := rand.Intn(4)
switch rd {
case 0:
p.BloodType = "A"
case 1:
p.BloodType = "B"
case 2:
p.BloodType = "AB"
default:
p.BloodType = "O"
}
ps = append(ps, p)
}
return ps
}
type TypeCounter struct {
A int
B int
AB int
O int
}
func (ps Persons) count() TypeCounter {
var counter TypeCounter
for _, p := range ps {
switch p.BloodType {
case "A":
counter.A++
case "B":
counter.B++
case "AB":
counter.AB++
default:
counter.O++
}
}
return counter
}
func main() {
ps := generateDummys(120)
cnt := ps.count()
fmt.Printf("Result %+v", cnt)
}
2. Using a map
Similar to the method using a struct, this approach uses a map.
// You can edit this code!
// Click here and start typing.
package main
import (
"fmt"
"math/rand"
"time"
)
type Person struct {
Id int
BloodType string
}
type Persons []Person
func generateDummys(size int) Persons {
rand.Seed(time.Now().UnixNano())
ps := make(Persons, 0, size)
for i := 0; i < size; i++ {
var p Person
p.Id = i
rd := rand.Intn(4)
switch rd {
case 0:
p.BloodType = "A"
case 1:
p.BloodType = "B"
case 2:
p.BloodType = "AB"
default:
p.BloodType = "O"
}
ps = append(ps, p)
}
return ps
}
func main() {
ps := generateDummys(120)
bloodType := map[string]int{
"A": 0,
"B": 0,
"AB": 0,
"O": 0,
}
for _, p := range ps {
switch p.BloodType {
case "A":
bloodType["A"]++
case "B":
bloodType["B"]++
case "AB":
bloodType["AB"]++
default:
bloodType["O"]++
}
}
fmt.Printf("Result %+v", bloodType)
}
Discussion