SoFunction
Updated on 2025-03-04

golang group slices or arrays based on a field

I won't say much nonsense, let's just read the code ~

package main
import (
 "fmt"
 "sort"
)
type Person struct {
 Name string
 Age int
}
func main() {
 p1 := Person{"Tom",20}
 p2 := Person{"Lily",21}
 p3 := Person{"Linda",23}
 p4 := Person{"Jass",25}
 p5 := Person{"Tonny",20}
 p6 := Person{"Pite",25}
 p7 := Person{"Paul",21}
 p8 := Person{"Kriss",27}
 p9 := Person{"Jake",23}
 p10 := Person{"Rose",20}
 personList := []Person{}
 personList = append(personList,p1,p2,p3,p4,p5,p6,p7,p8,p9,p10)
 ("Data before grouping:",personList)
 ("Translated data:",splitSlice(personList))
}
//Sort by a fieldtype sortByAge []Person
func (s sortByAge) Len() int   { return len(s) }
func (s sortByAge) Swap(i, j int)  { s[i], s[j] = s[j], s[i] }
func (s sortByAge) Less(i, j int) bool { return s[i].Age < s[j].Age}
//Slice groupingfunc splitSlice(list []Person) [][]Person {
 (sortByAge(list))
 returnData := make([][]Person,0)
 i:= 0
 var j int
 for {
 if i >= len(list) {
 break
 }
 for j = i + 1; j< len(list) && list[i].Age == list [j].Age; j++ {}
 returnData = append(returnData,list[i:j])
 i = j
 }
 return returnData
}

The printing results are as follows:

Data before grouping:

[{Tom 20} {Lily 21} {Linda 23} {Jass 25} {Tonny 20} {Pite 25} {Paul 21} {Kriss 27} {Jake 23} {Rose 20}]

Grouped data:

[[{Tom 20} {Rose 20} {Tonny 20}] [{Lily 21} {Paul 21}] [{Linda 23} {Jake 23}] [{Pite 25} {Jass 25}][{Kriss 27}]]

Supplement: golang grouping and enumeration

I won't say much nonsense, let's just read the code~

package main
//Import multiple packages at the same time//import “fmt”
//import “errors”
//Declare multiple constants or variables at the same time, then it can be simplified to the following group declaration method//const PI float32 = 3.14
//const NAME string = “hello”
//Group Statementimport(
“fmt”
“errors”
)
//Constant declaration is capitalized, just like c/c++const(
PI = 3.14
NAME = “HELLO”
)
//Enum enum, like c/c++, starts from 0// iota enumeration, default equal to 0. If no variable is declared in the same group, then iota adds 1 so y=1, z=2, j = 5const(
// x = iota
// y = iota
// z = iota
x = iota
y = iota
z = 6
k  
p
j = iota
)
// When encountering a new const eun, iota will be reset to 0, so h = 0const(
h = iota
)
//Golang Design Principles//Variables starting with uppercase letters can be used by other packages. Variables starting with lowercase letters can only be used by the current package//The function is also pulled, uppercase can be used by other packages, lowercase can only be used by the current package.func main() {
err := (“hello”)
(err)
//x=0 y=1 z=2 h=0
// x=0 y=1 z=6 h=0 k=6 j=5
("x=%d y=%d z=%d h=%d k=%d j=%d\n", x,y,z,h,k,j)
}

The above is personal experience. I hope you can give you a reference and I hope you can support me more. If there are any mistakes or no complete considerations, I would like to give you advice.