结构体排序-接口应用
实现 sort
包的Interface
接口,就可以快速排序。 接口的妙用
package main
import (
"fmt"
"math/rand"
"sort"
)
type Hero struct {
Name string
Age int
}
type HeroSlice []Hero
func (H HeroSlice)Len()int{
return len(H)
}
func (H HeroSlice)Less(i,j int)bool{
return H[i].Age < H[j].Age
}
func (H HeroSlice)Swap(i,j int){
temp := H[i]
H[i] = H[j]
H[j] = temp
}
func main(){
var Her HeroSlice
for i:=0;i<10;i++{
h := Hero{
Name: fmt.Sprintf("英雄~%d",i),
Age: i * rand.Intn(100),
}
fmt.Println(h)
Her = append(Her,h)
}
//fmt.Println(Her)
sort.Sort(Her)
fmt.Println("排序后...")
for _,v := range Her{
fmt.Println(v)
}
}