Programming languages often provide ready-made helpers for sorting collections due to the incredibly common nature of this task. Go is no different with its provision of the sort package for all your sorting needs.
Sorting data is one of the most common tasks you may find yourself performing ever so often. This article explores a few techniques in Go that should make the sorting of any data collection a breeze.
Sort a slice of strings
The sort.Strings method sorts a slice of strings in increasing order as shown below:
The sort.StringsAreSorted method also exists to help you check if a string slice is in its sorted form (that is, in increasing order):
Sort a slice of integers
To sort a slice of integers, use the sort.Ints method as shown below:
Sort a slice of floats
A slice of float64s may be sorted in increasing order using sort.Float64s:
Sort a slice of structs
To sort a slice of structs in Go, you need to use a less function along with either the sort.Slice or sort.SliceStable methods. Here’s how we can sort a slice of persons according to their names and ages for example:
Returning true from the less function will cause the element at index i to be sorted to a lower position than index j (The element at index i will come first in the sorted slice). Otherwise, the element at index j will come first if false is returned.
The difference between sort.Slice and sort.SliceStable is that the latter will keep the original order of equal elements while the former may not.
Sort a struct slice using multiple keys
In the example below, we’ll sort a slice of Person structs by LastName, and then by FirstName so that if two people have the same LastName, they’ll be ordered according to their first names.
Sort a map by key or value
Maps are unordered collections in Go so there is no provision for sorting a map using the sort package. However, if you really need to sort a map, you can try the methods described below.
From Go 1.12, you can just print the map and it’ll be sorted by keys:
If you intend to do more than just print the sorted map or if you want to sort by value instead, you can create an empty slice of key-value pairs whose capacity is equal to the length of the map, iterate over the map and add an entry for each key-value pair to the slice, then sort the slice using sort.SliceStable. Once the slice is sorted, you can iterate over it and access the map value associated with the key.
Sorting collections of data is pretty straightforward in Go through the use of the sort package and the solutions presented above should suffice for the majority of situations you will face. If you know of a different way to sort that is not covered in this article, please do share it in the comments section below.