//实现Hero结构体切片的排序:sort.Sort(data Interface)
import (
"fmt"
"math/rand"
"sort"
)
//1.首先声明一个结构体,叫Hero结构体
type Hero struct {
Name string
Age int
}
//2.声明一个Hero结构体切片类型
type HeroSlice []Hero
//3.实现Interface接口
//Interface 表明需要实现的三个方法。
// type Interface interface {
// // Len is the number of elements in the collection.
// Len() int
// //Less reports whether the element with
// //index i should sort before the element with index j.
// Less(i, j int) bool
// //Swap swaps the elements with indexes i and j.
// Swap(i, j int)
// }
//1.Len
func (hs HeroSlice) Len() int {
return len(hs)
}
//2.less 决定是使用什么标准来进行排序
func (hs HeroSlice) Less(i, j int) bool {
return hs[i].Age > hs[j].Age
//return hs[i].Name > hs[j].Name
}
//3.Swap
func (hs HeroSlice) Swap(i, j int) {
hs[i], hs[j] = hs[j], hs[i]
}
type Student struct {
Name string
Age int
Score float64
}
type StudentSlice []Student
//student的实现接口的三个函数
func (st StudentSlice) Len() int {
return len(st)
}
//2.less 决定是使用什么标准来进行排序
func (st StudentSlice) Less(i, j int) bool {
return st[i].Score > st[j].Score
//return st[i].Name > st[j].Name
}
func (st StudentSlice) Swap(i, j int) {
st[i], st[j] = st[j], st[i]
}
func main() {
//先定义 一个数组/切片
var intSlice = []int{-1, 0, 10, 90}
sort.Ints(intSlice) //直接对切片进行排序,在其内部进行排序会直接影响到这个切片
fmt.Println(intSlice)
//基于通用性的考虑,使用系统提供的方法来对结构体进行排序
var heroes HeroSlice
for i := 0; i < 10; i++ {
hero := Hero{
Name: fmt.Sprintf("英雄~%d", rand.Intn(100)),
Age: rand.Intn(100),
}
heroes = append(heroes, hero)
}
//先看看排序前的顺序
for _, v := range heroes {
fmt.Println(v)
}
sort.Sort(heroes)
//再看看排序后的顺序
fmt.Println("-----------排序后的顺序-----------")
for _, v := range heroes {
fmt.Println(v)
}
//实现student的方式
var st StudentSlice
for i := 0; i < 10; i++ {
smallst := Student{
Name: fmt.Sprintf("学生~%d", rand.Intn(100)),
Age: rand.Intn(100),
Score: float64(rand.Intn(100)),
}
st = append(st, smallst)
}
//先看看排序前的顺序
for _, v := range st {
fmt.Println(v)
}
sort.Sort(st)
//再看看排序后的顺序
fmt.Println("-----------排序后的顺序-----------")
for _, v := range st {
fmt.Println(v)
}
}
GO语言学习日记:实现Sort接口
最新推荐文章于 2024-05-07 14:41:53 发布