How to use sort package

Use the sort package to arrange slices of integers, strings, or custom types in ascending or descending order.

The sort package provides functions and types to sort slices of basic types and custom types. Use sort.Ints for integers, sort.Strings for strings, or sort.Slice with a custom comparison function for complex types.

import "sort"

nums := []int{5, 2, 9, 1}
sort.Ints(nums) // [1, 2, 5, 9]

strings := []string{"banana", "apple"}
sort.Strings(strings) // ["apple", "banana"]

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
})