一、给结构体数组排序
package main
import (
"fmt"
"math/rand"
"sort"
)
//声明一个结构体
type Hero struct {
Name string
Age int
}
//声明一个结构体切片
type HeroSlice []Hero
//实现Interface接口
func (hs *HeroSlice) Len() int {
return len(*hs)
}
func (hs *HeroSlice) Less(i,j int) bool{
//return (*hs)[i].Age < (*hs)[j].Age
return (*hs)[i].Name < (*hs)[j].Name
}
func (hs *HeroSlice) Swap(i,j int) {
//temp := (*hs)[i]
//(*hs)[i] = (*hs)[j]
//(*hs)[j] = temp
//简洁写法
(*hs)[i],(*hs)[j] = (*hs)[j],(*hs)[i]
}
func main() {
//定义一个切片数组
ints := []int{0, 5, 2, 6, 7}
//使用系统方法排序
sort.Ints(ints)
fmt.Println(ints)
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)
}
sort.Sort(&heroes)
for _, value := range heroes {
fmt.Println(value)
}
}