Home >Backend Development >Golang >How to Reverse-Sort a Slice of Integers in Go?
How to Reverse-Sort a Slice of Integers in Go
In Go, you can encounter the need to reverse-sort a slice of integers, where the highest number is listed first. This is different from the default sorting behavior, which sorts from lowest to highest.
To achieve reverse sorting, you cannot simply combine sort.Ints and sort.Reverse. Using sort.Ints creates a convenience function for sorting a few ints, while sort.Reverse expects a type that implements the sort.Interface interface. However, the sort package provides a predefined type called IntSlice that solves this issue:
Solution:
keys := []int{3, 2, 8, 1} sort.Sort(sort.Reverse(sort.IntSlice(keys))) fmt.Println(keys) // Output: [8 3 2 1]
IntSlice is a slice of integers that implements sort.Interface, meaning it can be sorted by its Less method. sort.Reverse creates a new type that reverses the order of Less, effectively providing reverse sorting.
This method allows you to reverse-sort slices of integers efficiently without the need for custom sorting algorithms or complicated interfaces.
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!