To sort an array in descending order in Go, you can use the `sort.Slice` function with a custom comparison function.
In this example,
numbers
.sort.Slice
function with a custom comparison function to sort the array of integers in descending order.package main
import (
"fmt"
"sort"
)
func main() {
numbers := []int{5, 2, 8, 1, 9}
sort.Slice(numbers, func(i, j int) bool {
return numbers[i] > numbers[j]
})
fmt.Println(numbers)
}
[9 8 5 2 1]
In this example,
words
.sort.Slice
function with a custom comparison function to sort the array of strings in descending order.package main
import (
"fmt"
"sort"
)
func main() {
words := []string{"apple", "banana", "cherry", "date"}
sort.Slice(words, func(i, j int) bool {
return words[i] > words[j]
})
fmt.Println(words)
}
[date cherry banana apple]
In this tutorial, we learned How to Sort an Array in Descending Order in Go language with well detailed examples.