Home > Article > Backend Development > How to Reverse Sort a Slice of Integers in Go?
Reverse Sorting a Slice of Integers in Go
You seek to reverse-sort a slice of integers in Go, similar to how the built-in sort.Ints function sorts them from lowest to highest.
Custom Implementation:
You attempted to utilize sort.Ints followed by sort.Reverse, but encountered an error. The issue is that sort.Ints returns a value that cannot be used as a sort.Interface.
IntSlice Type:
The sort package conveniently provides IntSlice, a predefined type that implements the sort.Interface. By using this type, you can achieve reverse sorting with ease. Here's how to accomplish it:
package main import ( "fmt" "sort" ) func main() { keys := []int{3, 2, 8, 1} sort.Sort(sort.Reverse(sort.IntSlice(keys))) fmt.Println(keys) }
This code sorts the slice keys in reverse order, effectively from highest to lowest. The output will be:
[8 3 2 1]
The above is the detailed content of How to Reverse Sort a Slice of Integers in Go?. For more information, please follow other related articles on the PHP Chinese website!