How to do custom sort in Go

The sort.Interface

In go, we can do sort with sort.Sort function. The sort.Sort function take sort.Interface as argument. The sort.Interface requires 3 methods: Len() int, Less() bool and Swap()

Example 1: Sort people by name

In this example, we will sort a list of Person by their Name

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package main

import (
	"fmt"
	"sort"
)

// Person struct
type Person struct {
	Name string
	Age  int
}

// Create a ByName type to make it become sort.Interface
type ByName []Person

// return len of the list
func (people ByName) Len() int {
	return len(people)
}

// Define how to sort
func (people ByName) Less(i, j int) bool {
	return people[i].Name < people[j].Name
}

// Just swapping two element
func (people ByName) Swap(i, j int) {
	people[i], people[j] = people[j], people[i]
}

func main() {
	myFriends := []Person{
		{"John", 22},
		{"Tom", 20},
		{"Dave", 26},
	}
	sort.Sort(ByName(myFriends))
	fmt.Println(myFriends)
}

This program will print the following result:

1
[{Dave 26} {John 22} {Tom 20}]

Example 2: Sort people by Age

This is how to sort these people by their age

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
package main

import (
	"fmt"
	"sort"
)

// Person struct
type Person struct {
	Name string
	Age  int
}

// Create a ByAge type to make it become sort.Interface
type ByAge []Person

// return len of the list
func (people ByAge) Len() int {
	return len(people)
}

// Define how to sort
func (people ByAge) Less(i, j int) bool {
	return people[i].Age < people[j].Age
}

// Just swapping two element
func (people ByAge) Swap(i, j int) {
	people[i], people[j] = people[j], people[i]
}

func main() {
	myFriends := []Person{
		{"John", 22},
		{"Tom", 20},
		{"Dave", 26},
	}
	sort.Sort(ByAge(myFriends))
	fmt.Println(myFriends)
}

This program will print people sorted by their Age

1
[{Tom 20} {John 22} {Dave 26}]