package main
import (
"fmt"
"math/rand"
"sort"
)
//学生结构体
type Student struct {
Name string
Id string
Age int
}
type StudentArray []Student
// 实现sort 接口 Len方法返回集合中的元素个数
//以下三个方法 实现了sort接口的 三个方法,所以可以直接调用sort接口进行排序
func (p StudentArray) Len() int {
return len(p)
}
//比较大小
func (p StudentArray) Less(i, j int) bool {
return p[i].Name > p[j].Name
}
//交换元素
func (p StudentArray) Swap(i, j int) { p[i], p[j] = p[j], p[i] }func main() { var stus StudentArray for i := 0; i < 10; i++ { stu := Student{ Name: fmt.Sprintf("stu%d", rand.Intn(100)), Id: fmt.Sprintf("110%d", rand.Int()), Age: rand.Intn(100), } stus = append(stus, stu) }
for _, v := range stus { fmt.Println(v) }
sort.Sort(stus)
for _, v := range stus { fmt.Println(v) } } 标签:sort,stus,StudentArray,自定义,rand,fmt,接口,排序 From: https://www.cnblogs.com/chenweihao/p/16600432.html