Home >Backend Development >Golang >How to Reverse-Sort an Integer Slice in Go?
Reverse-Sorting an Integer Slice in Go
In Go, you might encounter the need to sort a slice of integers in descending order (highest to lowest). While the sort.Ints function provides a straightforward way to sort values in ascending order, it doesn't offer an option for reverse sorting.
To achieve reverse sorting, you mistakenly tried using sort.Sort(sort.Reverse(sort.Ints(keys))) in conjunction with the sort.Reverse function. However, sort.Ints is designed for direct use with the sort function on int arrays, and trying to use it as a value within sort.Sort results in a compilation error.
The solution lies in utilizing the predefined IntSlice type provided by the sort package, which implements the sort.Interface interface. This type enables you to implement custom sorting strategies, including reverse sorting.
Example:
keys := []int{3, 2, 8, 1} sort.Sort(sort.Reverse(sort.IntSlice(keys))) fmt.Println(keys) // Output: [8 3 2 1]
By using sort.IntSlice and its Reverse implementation, you can effectively reverse-sort your slice of integers in Go.
The above is the detailed content of How to Reverse-Sort an Integer Slice in Go?. For more information, please follow other related articles on the PHP Chinese website!