Go语言中接口的简单应用示例

实现sort.Interface接口

任何实现了 sort.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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
type Student struct {
Name string
Age int
}

type StudentArray []Student

// Len 为集合内元素的总数
func (this StudentArray) Len() int {
return len(this)
}

// Less 返回索引为 i 的元素是否应排在索引为 j 的元素之前。
func (this StudentArray) Less(i, j int) bool {
return this[i].Age < this[j].Age
}

// Swap 交换索引为 i 和 j 的元素
func (this StudentArray) Swap(i, j int) {
this[i], this[j] = this[j], this[i]
}

func main() {
var stuArr StudentArray
for i := 0; i < 15; i++ {
stu := Student{
Name: fmt.Sprintf("stu%d", rand.Intn(100)),
Age: rand.Intn(100),
}
stuArr = append(stuArr, stu)
}
fmt.Println("排序前:")
for _, v := range stuArr {
fmt.Printf("name:%v,age:%d\n", v.Name, v.Age)
}

sort.Sort(stuArr)
fmt.Println("排序后:")
for _, v := range stuArr {
fmt.Printf("name:%v,age:%d\n", v.Name, v.Age)
}
}
------------------------
排序前:
name:stu81,age:87
name:stu47,age:59
name:stu81,age:18
name:stu25,age:40
name:stu56,age:0
name:stu94,age:11
name:stu62,age:89
name:stu28,age:74
name:stu11,age:45
name:stu37,age:6
name:stu95,age:66
name:stu28,age:58
name:stu47,age:47
name:stu87,age:88
name:stu90,age:15
排序后:
name:stu56,age:0
name:stu37,age:6
name:stu94,age:11
name:stu90,age:15
name:stu81,age:18
name:stu25,age:40
name:stu11,age:45
name:stu47,age:47
name:stu28,age:58
name:stu47,age:59
name:stu95,age:66
name:stu28,age:74
name:stu81,age:87
name:stu87,age:88
name:stu62,age:89