While recently working on an piece of Go code I found myself wondering: how can you sort by multiple fields? Imagine you have a struct slice and you want to sort it based on multiple fields of the struct.

Here’s an example of a struct representing a simple bank account:

type Account struct {
	AccountID    int
	Balance      int
	LastUpdated  int
	Created      int
	Transactions []int
}

And a slice of the Account struct:

var accounts = []Account{}

We want to sort the accounts slice by the Balance field and if Balance is the same then by AccountID.

Lets take a simple case first: sort all the accounts by their Balance in decending order:

sort.Slice(accounts, func(i,j int) bool {
  return accounts[i].Balance > accounts[j].Balance
})

Here the helper function returns true if the account at index i in the slice has balance greater than account at index j.

Now coming to the actual problem:

sort.Slice(accounts, func(i,j int) bool {
  if accounts[i].Balance == accounts[j].Balance {
    return accounts[i].AccountID > accounts[j].AccountID
  } else {
    return accounts[i].Balance > accounts[j].Balance
  }
})

Thats it! We start by setting up the helper function in a similar fashion but add an if condition: If the balances are same then sort (descending) by AccountId. But if the balances are not the same then sort it as per previously - by Balance.