day9接口 练习7.8

master
独孤伶俜 2022-12-17 12:31:43 +08:00
parent 7a8e1a2a6d
commit 6a1339b1f2
1 changed files with 71 additions and 0 deletions

View File

@ -0,0 +1,71 @@
package main
import (
"fmt"
"reflect"
"sort"
)
// 很多图形界面提供了一个有状态的多重排序表格插件:
// 主要的排序键是最近一次点击过列头的列,第二个排序键是第二最近点击过列头的列,等等。
// 定义一个sort.Interface的实现用在这样的表格中。
// 比较这个实现方式和重复使用sort.Stable来排序的方式。
// 1. 定义数据
// 2. 实现sort.Interface
// 3. 实现可复用的排序方法
// 4. 实现点击一栏就对一栏排序
// 1. 定义数据类型
type Person struct {
Name string
Age int
Sex bool
ID int
}
type PersonSlice []Person
// Less 没有实现sort.Interface的Less方法
func (p PersonSlice) Less(i, j int, field string) bool {
return PersonByField(p[i], p[j], field)
}
// PersonByField 按照字段排序
func PersonByField(i, j Person, field string) bool {
switch field {
case "Name":
return i.Name > j.Name
case "Age":
return i.Age < j.Age
case "Sex":
return i.Sex != j.Sex
case "ID":
return i.ID < j.ID
}
return false
}
func main() {
// 构建数据
data := PersonSlice{
{"a", 1, true, 1},
{"b", 2, false, 2},
{"c", 3, true, 3},
{"d", 4, false, 4},
{"e", 5, true, 5},
{"f", 6, false, 6},
{"g", 7, true, 7},
}
// 排序
sort.Slice(data, func(i, j int) bool {
return data.Less(i, j, "Sex")
})
// 输出
for _, v := range data {
fmt.Println(v)
}
// 尝试使用反射解决可是发现不会233333
t, b := reflect.TypeOf(data[1]).FieldByName("Name")
fmt.Println(t, b)
}