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

How to Sort Structs by Multiple Parameters in Go?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-16 12:20:11323browse

How to Sort Structs by Multiple Parameters in Go?

Sorting Structs with Multiple Parameters

Question:

How can an array of structs be sorted by multiple parameters, specifically by last name and then first name in Go?

Answer:

There are several approaches to sorting structs with multiple parameters in Go.

Go 1.22 with slices.SortFunc

The latest version of Go (1.22 and later) offers a concise solution using slices.SortFunc:

slices.SortFunc(members, func(a, b Member) int {
    return cmp.Or(
        cmp.Compare(a.LastName, b.LastName),
        cmp.Compare(a.FirstName, b.FirstName),
    )
})

sort.Slice or sort.Sort Functions

For earlier versions of Go, consider using sort.Slice or sort.Sort. Both require a custom less function that determines the ordering based on the desired parameters.

With sort.Slice:

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
})

With sort.Sort:

Create a custom type that implements the sort.Interface interface, defining the Len, Swap, and Less methods.

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:

While these approaches provide different ways to sort structs, performance analysis is crucial to optimize for hot spots. Choose the approach that best suits your application's requirements.

The above is the detailed content of How to Sort Structs by Multiple Parameters in Go?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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