Normally, to sort an array of integers you wrap them in an IntSlice
, which defines the methods Len
, Less
, and Swap
. These methods are in turn used by sort.Sort
. What sort.Reverse
does is that it takes an existing type that defines Len
, Less
, and Swap
, but it replaces the Less
method with a new one that is always the inverse of the underlying Less
:
type reverse struct {
// This embedded Interface permits Reverse to use the methods of
// another Interface implementation.
Interface
}
// Less returns the opposite of the embedded implementation's Less method.
func (r reverse) Less(i, j int) bool {
return r.Interface.Less(j, i)
}
// Reverse returns the reverse order for data.
func Reverse(data Interface) Interface {
return &reverse{data}
}
So when you write sort.Reverse(sort.IntSlice(s))
, whats happening is that you're getting this new, 'modified' IntSlice
that has it's Less
method replaced. So if you call sort.Sort
on it, which calls Less
, it will get sorted in decreasing order.