How to Sort in Descending Order in Go: Simple Guide
sort.Slice function with a custom comparison that reverses the usual order. This involves passing a function that returns true when the first element is greater than the second, effectively sorting from largest to smallest.Syntax
The sort.Slice function sorts a slice based on a custom comparison function you provide. The syntax is:
sort.Slice(slice, func(i, j int) bool {
return slice[i] > slice[j]
})Here, slice is the slice you want to sort. The function compares elements at positions i and j. Returning true means the element at i should come before the element at j. Using > sorts in descending order.
sort.Slice(slice, func(i, j int) bool { return slice[i] > slice[j] })
Example
This example shows how to sort a slice of integers in descending order using sort.Slice. It prints the slice before and after sorting.
package main import ( "fmt" "sort" ) func main() { numbers := []int{5, 2, 9, 1, 7} fmt.Println("Before sorting:", numbers) sort.Slice(numbers, func(i, j int) bool { return numbers[i] > numbers[j] }) fmt.Println("After sorting in descending order:", numbers) }
Common Pitfalls
A common mistake is to use < in the comparison function, which sorts in ascending order instead of descending. Another pitfall is forgetting to import the sort package, which causes compilation errors.
Also, sorting a slice of structs requires accessing the correct field inside the comparison function.
package main import ( "fmt" "sort" ) func main() { numbers := []int{3, 8, 4} // Wrong: sorts ascending, not descending sort.Slice(numbers, func(i, j int) bool { return numbers[i] < numbers[j] // ascending order }) fmt.Println("Wrong ascending sort:", numbers) // Correct: descending order sort.Slice(numbers, func(i, j int) bool { return numbers[i] > numbers[j] }) fmt.Println("Correct descending sort:", numbers) }
Quick Reference
Remember these tips when sorting in descending order in Go:
- Use
sort.Slicewith a comparison function returningtruewhenslice[i] > slice[j]. - Import the
sortpackage. - For slices of structs, compare the desired field inside the function.
- Use
sort.SliceStableif you want to keep the original order of equal elements.
Key Takeaways
< sorts ascending; use > for descending order.