From 6a1339b1f24d5eb713b4f6776f9cb25120d102bd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=8B=AC=E5=AD=A4=E4=BC=B6=E4=BF=9C?= <1184662350@qq.com> Date: Sat, 17 Dec 2022 12:31:43 +0800 Subject: [PATCH] =?UTF-8?q?day9=E6=8E=A5=E5=8F=A3=20=E7=BB=83=E4=B9=A07.8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/study/day9Interface/Practice/7.8.go | 71 +++++++++++++++++++++++++ 1 file changed, 71 insertions(+) create mode 100644 src/study/day9Interface/Practice/7.8.go diff --git a/src/study/day9Interface/Practice/7.8.go b/src/study/day9Interface/Practice/7.8.go new file mode 100644 index 0000000..2c4335e --- /dev/null +++ b/src/study/day9Interface/Practice/7.8.go @@ -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) +}