How to Sort Custom Types in Go

Implement Len, Less, and Swap methods on your type to satisfy sort.Interface, then call sort.Sort to order your custom data.

To sort custom types in Go, implement the sort.Interface methods (Len, Less, Swap) on your type and call sort.Sort.

import "sort"

type Item struct {
    Name string
    Value int
}

type ByValue []Item

func (s ByValue) Len() int           { return len(s) }
func (s ByValue) Swap(i, j int)      { s[i], s[j] = s[j], s[i] }
func (s ByValue) Less(i, j int) bool { return s[i].Value < s[j].Value }

items := []Item{{"A", 2}, {"B", 1}}
sort.Sort(ByValue(items))