只要結(jié)構(gòu)體(集合)實(shí)現(xiàn)了Less层亿、Swap幻馁、Len三個(gè)方法即可使用sort包相關(guān)方法實(shí)現(xiàn)排序等操作提鸟。
代碼如下:
import (
"fmt"
"sort"
)
type student struct{
name string
age int
}
type stuSlice []student
func (s stuSlice)Len()int{
return len(s)
}
func (s stuSlice)Less(i,j int)bool{
return s[i].age<s[j].age
}
func (s stuSlice)Swap(i,j int){
s[i],s[j] = s[j],s[i]
}
func main(){
s:=stuSlice{}
s = append(s,student{name:"xiaohong",age:29})
s = append(s,student{name:"zhangsan3",age:18})
s = append(s,student{name:"zhangsan",age:14})
s = append(s,student{name:"zhangsan2",age:17})
sort.Sort(s)
fmt.Println("排序后結(jié)果:",s)
sort.Sort(sort.Reverse(s))
fmt.Println("逆序后結(jié)果:",s)
}