Go: how to sort a slice of structs

In Go, sorting a slice containing structs can be done using the sort package. This package provides the sort.Slice function, which allows you to define a custom sorting criterion.

Sorting Example

Let’s consider a Person struct with fields Name and Age. The goal is to sort a slice of Person by age.

package main

import (
	"fmt"
	"sort"
)

type Person struct {
	Name string
	Age  int
}

func main() {
	people := []Person{
		{Name: "Alice", Age: 30},
		{Name: "Bob", Age: 25},
		{Name: "Charlie", Age: 35},
	}

	sort.Slice(people, func(i, j int) bool {
		return people[i].Age < people[j].Age
	})

	fmt.Println("Sorted slice:", people)
}

Explanation

  • sort.Slice takes the slice and a comparison function that defines the order.
  • The comparison function returns true if the element at position i should come before the one at position j.
  • In the example, the slice is sorted in ascending order by age.

Custom Sorting

If you need more complex sorting, you can implement the sort.Interface interface:

type ByName []Person

func (p ByName) Len() int           { return len(p) }
func (p ByName) Swap(i, j int)      { p[i], p[j] = p[j], p[i] }
func (p ByName) Less(i, j int) bool { return p[i].Name < p[j].Name }

func main() {
	people := []Person{
		{Name: "Alice", Age: 30},
		{Name: "Bob", Age: 25},
		{Name: "Charlie", Age: 35},
	}

	sort.Sort(ByName(people))

	fmt.Println("Slice sorted by name:", people)
}

This approach is useful when you want to reuse the sorting criteria in multiple parts of your code.

Conclusion

Go provides simple and effective ways to sort slices of structs. sort.Slice is great for quick and customizable sorts, while sort.Interface offers greater reusability and flexibility.

Back to top