How to Sort Structs with Multiple Parameters
In Go, when sorting a slice of structs, it's often useful to consider multiple sorting parameters. For example, we may want to sort members first by their last name and then by their first name.
One way to achieve this is by using the slices.SortFunc function introduced in Go 1.22. slices.SortFunc allows us to specify a custom comparison function:
slices.SortFunc(members, func(a, b Member) int { return cmp.Or( cmp.Compare(a.LastName, b.LastName), cmp.Compare(a.FirstName, b.FirstName), ) })
Here, we use cmp.Or to apply both last name and first name comparisons. cmp.Compare returns an integer indicating equality (0), greater than (1), or less than (-1).
Another option, available since Go 1.8, is to use the sort.Slice or sort.Sort functions with a custom less function:
sort.Sort(byLastFirst(members))
Here, we define a custom byLastFirst type that implements the Len, Swap, and Less methods of the sort.Interface interface. The Less method checks both last name and first name for comparisons.
Which approach to choose depends on the version of Go you're using and the convenience it offers for your specific application. However, unless sorting proves to be a performance bottleneck, the most convenient approach is generally preferred.
The above is the detailed content of How to Sort Structs in Go Using Multiple Parameters?. For more information, please follow other related articles on the PHP Chinese website!