How to Sort a Slice in Go (sort.Slice and slices.Sort)

Use slices.Sort for basic types and sort.Slice for custom types or logic to order Go slices.

Use slices.Sort for built-in types like []int and sort.Slice for custom types or complex logic.

import "slices"

nums := []int{3, 1, 4, 1, 5}
slices.Sort(nums) // In-place sort for []int

// For custom types or custom logic
import "sort"

type Person struct {
    Name string
    Age  int
}
people := []Person{{"Alice", 30}, {"Bob", 25}}
sort.Slice(people, func(i, j int) bool {
    return people[i].Age < people[j].Age
})