To sort items of a Set in Go, you can convert the Set to a slice and use the sort
package.
In this example,
numberSet
using a map where the keys represent the numbers.numbers
.numbers
using the sort.Ints()
function from the sort
package.package main
import (
"fmt"
"sort"
)
func main() {
numberSet := map[int]struct{}{5: {}, 3: {}, 8: {}, 1: {}, 2: {}}
numbers := make([]int, 0, len(numberSet))
for num := range numberSet {
numbers = append(numbers, num)
}
sort.Ints(numbers)
fmt.Println("Sorted slice:", numbers)
}
Sorted slice: [1 2 3 5 8]
In this example,
stringSet
using a map where the keys represent the strings.strings
.strings
using the sort.Strings()
function from the sort
package.package main
import (
"fmt"
"sort"
)
func main() {
stringSet := map[string]struct{}{"banana": {}, "apple": {}, "cherry": {}, "date": {}}
strings := make([]string, 0, len(stringSet))
for str := range stringSet {
strings = append(strings, str)
}
sort.Strings(strings)
fmt.Println("Sorted slice:", strings)
}
Sorted slice: [apple banana cherry date]
In this tutorial, we learned How to Sort Items of a Set in Go language with well detailed examples.