Sorting Slices

Let’s learn how slices are sorted in Go.

There are times when we want to present our information sorted, and we want Go to do the job for us. In this lesson, we’ll see how to sort slices of various standard data types using the functionality offered by the sort package.

The sort package

The sort package can sort slices of built-in data types without the need to write any extra code. Additionally, Go provides the sort.Reverse() function for sorting in reverse rather than the default order. However, what is really interesting is that sort allows us to write our own sorting functions for custom data types by implementing the sort.Interface interface.

So, we can sort a slice of integers saved as sInts by typing sort.Ints(sInts). When sorting a slice of integers in reverse order using sort.Reverse(), we need to pass the desired slice to sort.Reverse() using sort.IntSlice(sInts) because the IntSlice type implements the sort.Interface internally, which allows us to sort in a different way than usual. The same applies to the other standard Go data types.

Coding example

The following sortSlice.go program illustrates the use of sort.

Get hands-on with 1200+ tech skills courses.