In Go, if you have a slice of simple type like []int
, []string
, or []float64
, you can sort the slice using the sort.Ints()
, sort.Strings()
, or sort.Float64s()
functions. However, they only sort a slice in ascending order. To sort in descending order, you must use the more general function sort.Sort()
with the data reversal function sort.Reverse()
.
|
|
Output:
[0 1 2 3 4 4 5 7]
[7 5 4 4 3 2 1 0]
[c b a]
Look at the example. To sort a []int
slice in descending order you need to:
- Convert the
[]int
slice tosort.IntSlice
, which makes the slice an instance of thesort.Interface
interface. - Reverse the standard ascending order of the elements included in the
sort.IntSlice
by using thesort.Reverse()
function. - Sort the reversed slice using the general
sort.Sort()
function.
The same scheme applies when sorting a []string
or []float64
list, but it must be converted to sort.StringSlice
or sort.Float64Slice
.
There is no built-in option to reverse the order when using the sort.Slice()
with a custom sorting function less
. However, we can do it ourselves. In the example below, the reverse()
function “reverses” the less
function. This way, we can create a single less
function for sorting a slice of structs and then sort it in ascending or descending order depending on a parameter or use case.
|
|
Output:
[{Raspberry pink 1} {Strawberry red 2} {Banana yellow 3}]
[{Banana yellow 3} {Strawberry red 2} {Raspberry pink 1}]