结构体排序需要实现Interface接口,实现其中三个方法。

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
package main

import (
"fmt"
"math/rand"
"sort"
)

// 接口最佳实践
func main() {
intSlice := []int{-2, 60, 3, 6, 2, 99, 78, 22}
// 排序
sort.Ints(intSlice)
fmt.Println(intSlice)
fmt.Println("----------------/学生结构体切片排序前\\----------------------")
var stuSlice studentSlice
for i := 0; i < 10; i++ {
stu := student{
name: fmt.Sprintf("清清~%d", i),
age: rand.Intn(100) + 1,
score: float64(rand.Intn(101)),
}
stuSlice = append(stuSlice, stu)
}
fmt.Println(stuSlice)
fmt.Println("----------------/学生结构体切片排序后\\----------------------")
sort.Sort(stuSlice)
fmt.Println(stuSlice)

}

type student struct {
name string
age int
score float64
}
type studentSlice []student

// Len 返回切片长度
func (stuSlice studentSlice) Len() int {
return len(stuSlice)
}

// Less 排序规则
func (stuSlice studentSlice) Less(i, j int) bool {
//return stuSlice[i].score < stuSlice[j].score // 分数升序
return stuSlice[i].name > stuSlice[j].name
}

// Swap 满足排序规则就交换
func (stuSlice studentSlice) Swap(i, j int) {
stuSlice[i], stuSlice[j] = stuSlice[j], stuSlice[i]
}