Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort struct with multiple sort parameters?

Tags:

sorting

go

I have an array/slice of members:

type Member struct {     Id int     LastName string     FirstName string }  var members []Member 

My question is how to sort them by LastName and then by FirstName.

like image 723
Melvin Avatar asked Mar 21 '16 03:03

Melvin


1 Answers

Use the sort.Slice (available since Go 1.8) or the sort.Sort function to sort a slice of values.

With both functions, the application provides a function that tests if one slice element is less than another slice element. To sort by last name and then first name, compare last name and then first name:

if members[i].LastName < members[j].LastName {     return true } if members[i].LastName > members[j].LastName {     return false } return members[i].FirstName < members[j].FirstName 

The less function is specified using an anonymous function with sort.Slice:

var members []Member sort.Slice(members, func(i, j int) bool {     if members[i].LastName < members[j].LastName {         return true     }     if members[i].LastName > members[j].LastName {         return false     }     return members[i].FirstName < members[j].FirstName }) 

The less function is specified with through an interface with the sort.Sort function:

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 true     }     if members[i].LastName > members[j].LastName {        return false     }     return members[i].FirstName < members[j].FirstName }  sort.Sort(byLastFirst(members)) 

Unless performance analysis shows that sorting is a hot spot, use the function that's most convenient for your application.

like image 137
Bayta Darell Avatar answered Sep 17 '22 14:09

Bayta Darell