Sorting Structs with Multiple Criteria
In Go, sorting a slice of structs can be achieved using various approaches. This discussion focuses on sorting by multiple parameters, specifically by LastName and then FirstName.
Method 1: slices.SortFunc (Go 1.22 )
For Go 1.22 and above, slices.SortFunc provides an elegant solution:
slices.SortFunc(members, func(a, b Member) int { return cmp.Or( cmp.Compare(a.LastName, b.LastName), cmp.Compare(a.FirstName, b.FirstName), ) })
Method 2: sort.Slice or sort.Sort
In Go 1.8 , sort.Slice or sort.Sort can be used. Both require a less function to determine the ordering. This function compares the LastName and FirstName fields:
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 })
For sort.Sort, a custom type implementing the sort.Interface is needed:
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))
Performance Considerations
Choose the approach that best suits your application's requirements. Unless performance analysis reveals sorting to be a bottleneck, convenience should be prioritized.
The above is the detailed content of How to Sort Structs in Go by Multiple Criteria (LastName then FirstName)?. For more information, please follow other related articles on the PHP Chinese website!