Sorting data in Go requires you to implement the sort.Interface.
This interface requires three simple methods:
1 2 3
Define the Struct and Collection
1 2 3 4 5
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
Implement the Interface
1 2 3 4 5 6 7 8 9 10 11
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.
Countries type now provides all the methods to satisfy the
Sort All the Things
1 2 3 4 5 6 7 8 9 10 11 12 13 14
There you have it. A simple example of sorting a slice of structs in Go.
As always: Full Source