The slices.Sort
function in Go is used for sorting slices. It was introduced in Go 1.18 as part of the new generics features, providing a more straightforward and type-safe way to sort slices without needing to convert them to a specific type like sort.IntSlice
or sort.StringSlice
. Here are some examples demonstrating how to use slices.Sort
:
1. Sorting a Slice of Integers
package main
import (
"fmt"
"golang.org/x/exp/slices"
)
func main() {
numbers := []int{5, 3, 4, 1, 2}
slices.Sort(numbers)
fmt.Println(numbers) // Output: [1 2 3 4 5]
}
2. Sorting a Slice of Strings
package main
import (
"fmt"
"golang.org/x/exp/slices"
)
func main() {
strings := []string{"banana", "apple", "cherry"}
slices.Sort(strings)
fmt.Println(strings) // Output: [apple banana cherry]
}
3. Sorting a Slice of Custom Structs
To sort a slice of custom structs, you need to provide a comparison function.
package main
import (
"fmt"
"golang.org/x/exp/slices"
)
type Person struct {
Name string
Age int
}
func main() {
people := []Person{
{"Bob", 31},
{"Alice", 22},
{"John", 42},
}
// Sorting by Age
slices.SortFunc(people, func(a, b Person) bool {
return a.Age < b.Age
})
fmt.Println(people)
// Output: [{Alice 22} {Bob 31} {John 42}]
}
4. Using a Custom Comparison Function for Integers
You can also use slices.SortFunc
for basic types if you want to customize the sorting logic.
package main
import (
"fmt"
"golang.org/x/exp/slices"
)
func main() {
numbers := []int{5, 3, 4, 1, 2}
// Sort in descending order
slices.SortFunc(numbers, func(a, b int) bool {
return a > b
})
fmt.Println(numbers) // Output: [5 4 3 2 1]
}
Remember to import golang.org/x/exp/slices
as the slices
package is part of Go’s experimental packages and not included in the standard library. These examples demonstrate the ease and flexibility of using slices.Sort
and slices.SortFunc
for sorting slices in Go.