golang自定义排序需要实现 Len() Less() Swap() 三个方法

 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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package main

import (
	"fmt"
	"sort"
)

type Person struct {
	Name   string
	Age    int
	Height int
}

type ByAge []Person

func (p ByAge) Len() int {
	return len(p)
}

func (p ByAge) Less(i, j int) bool {
	return p[i].Age < p[j].Age
}

func (p ByAge) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

type ByHeight []Person

func (p ByHeight) Less(i, j int) bool {
	return p[i].Height < p[j].Height
}

func (p ByHeight) Len() int {
	return len(p)
}

func (p ByHeight) Swap(i, j int) {
	p[i], p[j] = p[j], p[i]
}

func main() {
	people := []Person{
		{Name: "zhangsan", Age: 20, Height: 185},
		{Name: "lisi", Age: 18, Height: 180},
		{Name: "wangwu", Age: 19, Height: 175},
		{Name: "pony", Age: 29, Height: 165},
	}
	fmt.Println(people)
	sort.Sort(ByAge(people))
	fmt.Println(people)
	sort.Sort(ByHeight(people))
	fmt.Println(people)
}