Sort Slices of Structs using Go sort.Slice

Jeff Roberts
InstructorJeff Roberts

Share this video with your friends

Send Tweet

There are numerous ways to sort slices in Go.

In this lesson, we will take a quick look at an easy way to sort a slice of structs or primitives. We will learn about using one of the handy built-in functions in Go's sort package called sort.Slice. This function takes a slice to sort as an argument and a less function or less func for short as the second argument. You will write this less function to sort the slice however you wish.

Go's sort.Slice function looks like this: sort.Slice(someSlice, func(i, j int) bool). It's super-easy to write an anonymous less function to sort.

As you will see, it's easy to use this less function to do simple and even complex sorts of your structs with minimal effort.