To sort a string array in Go in dictionary order, you can use the `sort.Strings()` function. To sort in descending order, you can use a custom compare function or reverse the array after sorting.
In this example,
package main
import (
"fmt"
"sort"
)
func main() {
words := []string{"banana", "apple", "orange", "grape"}
sort.Strings(words)
fmt.Println("Sorted Array Ascending:", words)
}
Sorted Array Ascending: [apple banana grape orange]
In this example,
package main
import (
"fmt"
"sort"
)
func main() {
words := []string{"banana", "apple", "orange", "grape"}
sort.Slice(words, func(i, j int) bool {
return words[i] > words[j]
})
fmt.Println("Sorted Array Descending:", words)
}
Sorted Array Descending: [orange grape banana apple]
In this tutorial, we learned How to Sort a String Array in Dictionary Order in Go language with well detailed examples.