Home > Backend Development > Golang > How to Sort Structs in Go by Multiple Fields (LastName then FirstName)?

How to Sort Structs in Go by Multiple Fields (LastName then FirstName)?

Patricia Arquette
Release: 2024-12-12 17:36:12
Original
197 people have browsed it

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

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

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!

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