Home >Backend Development >Golang >How to Sort Structs in Go by Multiple Fields (LastName then FirstName)?
How to Sort Structures with Multiple Parameters
In programming, it's often necessary to sort data based on multiple criteria. In Go, this can be achieved effectively using custom sorting functions.
Problem:
How do you sort a slice of structs by LastName and then FirstName?
Solution using slices.SortFunc (Go 1.22 ):
slices.SortFunc(members, func(a, b Member) int { return cmp.Or( cmp.Compare(a.LastName, b.LastName), cmp.Compare(a.FirstName, b.FirstName), ) })
This solution uses the slices.SortFunc function to compare structs by their LastName and FirstName fields in that order.
Solution using sort.Slice or sort.Sort:
sort.Slice(members, func(i, j int) bool { if members[i].LastName != members[j].LastName { return members[i].LastName < members[j].LastName } return members[i].FirstName < members[j].FirstName })
type byLastFirst []Member func (members byLastFirst) Len() int { return len(members) } func (members byLastFirst) Swap(i, j int) { members[i], members[j] = members[j], members[i] } func (members byLastFirst) Less(i, j int) bool { if members[i].LastName != members[j].LastName { return members[i].LastName < members[j].LastName } return members[i].FirstName < members[j].FirstName } sort.Sort(byLastFirst(members))
Both solutions compare the LastName fields first. If they are equal, they compare the FirstName fields. The result is a sorted slice of members by both fields.
The above is the detailed content of How to Sort Structs in Go by Multiple Fields (LastName then FirstName)?. For more information, please follow other related articles on the PHP Chinese website!