Complete Guide to the sort Package in Go

The sort package in Go provides functions to sort slices of basic types and custom data using comparison functions.

The sort package provides functions to sort slices of basic types and interfaces for custom data. Use sort.Slice with a custom comparison function to sort complex types.

package main

import (
	"fmt"
	"sort"
)

type Person struct {
	Name string
	Age  int
}

func main() {
	people := []Person{{"Alice", 30}, {"Bob", 25}, {"Charlie", 35}}
	sort.Slice(people, func(i, j int) bool {
		return people[i].Age < people[j].Age
	})
	fmt.Println(people)
}