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.
以上是如何在 Go 中對整數切片進行反向排序?的詳細內容。更多資訊請關注PHP中文網其他相關文章!