只要结构体(集合)实现了Less、Swap、Len三个方法即可使用sort包相关方法实现排序等操作。
代码如下:
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("排序后结果:",s)
sort.Sort(sort.Reverse(s))
fmt.Println("逆序后结果:",s)
}
网友评论