Golang sort slice

Starting Golang 1.8, this is one of the new way to sort slice available insort package

func Slice(slice interface{}, less func(i, j int) bool)

This function take two arguments.

The first argument is the slice you want to sort. sort.Slicewill sort this slice argument in place. Note, this function doesn’t return anything, it will sort the slice in place.

The second argument is a func that will be used during the sort. The function signature is

less func(i, j int) bool

These two notes could be helpful when implementing this method.

  • i and j are indexes of the argument slice . Element of index i comes after the element of index j . So when the function first got called, i = 1 and j = 0 . Note: i is after j index wise!
  • The function reports whether the element with index i should sort before the element with index j. For example, if you want to sort the slice in ascending order, the function body will be something like
return slice[i].Stuff < slice[j].Stuff