Home > Backend Development > Golang > How to Sort Structs in Go Using Multiple Parameters?

How to Sort Structs in Go Using Multiple Parameters?

Linda Hamilton
Release: 2024-12-11 10:03:17
Original
163 people have browsed it

How to Sort Structs in Go Using Multiple Parameters?

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),
    )
})
Copy after login

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))
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template