How to Implement the sort.Interface in Go

Implement sort.Interface by defining Len, Less, and Swap methods on a type to enable custom sorting with sort.Sort.

Implement the sort.Interface by defining a type with Len, Less, and Swap methods, then pass an instance to sort.Sort.

package main

import (
	"fmt"
	"sort"
)

type ByAge []Person

func (a ByAge) Len() int           { return len(a) }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
func (a ByAge) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }

type Person struct {
	Name string
	Age  int
}

func main() {
	people := []Person{{"Alice", 30}, {"Bob", 25}}
	sort.Sort(ByAge(people))
	fmt.Println(people)
}