HEY! I'm working on an awesome course on Golang and Ember.js skills that's live soon. Get early access to it here:

nerdyworm

Sorting a Slice of Structs in Go

Sorting data in Go requires you to implement the sort.Interface. This interface requires three simple methods: Len, Less, and Swap.

1
2
// returns the number of elements in the collection.
Len() int
1
2
3
// returns whether the element with index i should sort before
// the element with index j.
Less(i, j int) bool
1
2
// swaps the elements with indexes i and j.
Swap(i, j int)`

Define the Struct and Collection

1
2
3
4
5
type Country struct {
    Name string
}

type Countries []Country

First we declare our struct. For this example we are using only a single field which is a string. We also need to define our collection type so that we can satisfy the sort.Interface.

Implement the Interface

1
2
3
4
5
6
7
8
9
10
11
func (slice Countries) Len() int {
    return len(slice)
}

func (slice Countries) Less(i, j int) bool {
    return slice[i].Name < slice[j].Name;
}

func (slice Countries) Swap(i, j int) {
    slice[i], slice[j] = slice[j], slice[i]
}

The first method Len needs to return how many elements are in our collection. The built-in len function will work beautifully for this.

The second method is where we need to figure out which element comes before. For this example we just do a basic string comparison which will give us an ascending alphabetical sort order. If we wanted to sort descending we could just flip the < operator to >.

The last method actually performs the work of shuffling elements around. Go’s multiple assignment makes it easy to swap the values without having to explicitly declare a temporary variable.

The Countries type now provides all the methods to satisfy the sort.Interface interface.

Sort All the Things

1
2
3
4
5
6
7
8
9
10
11
12
13
14
func main() {
    countries := Countries{
        {Name: "United States"},
        {Name: "Bahamas"},
        {Name: "Japan"},
    }

    sort.Sort(countries)

    fmt.Println("\nSorted")
    for i, c := range countries {
        fmt.Println(i, c.Name)
    }
}

There you have it. A simple example of sorting a slice of structs in Go.

As always: Full Source

Comments