package main import( "fmt" "sort" "math/rand" ) //定义一个武当派的结构体 type Wudang struct{ Name string Age int Rating int //等级 } //定义一个Wudang结构切片类型 type Wudangslice []Wudang func (ws Wudangslice) Len() int { return len(ws) } func (ws Wudangslice) Less(i,j int) bool { return ws[i].Age < ws[j].Age } func (ws Wudangslice) Swap(i,j int) { ws[i],ws[j] = ws[j],ws[i] } func main(){ var wulin Wudangslice for i := 0;i < 8;i++ { wd := Wudang{ Name : fmt.Sprintf("武当%d号",rand.Intn(10)), Age:rand.Intn(100), Rating:rand.Intn(8), } wulin = append(wulin,wd) } //排序前的顺序 for _ , v:=range wulin{ fmt.Println(v) } //调用sort.Sort sort.Sort(wulin) fmt.Println("--------排序后-----------") for _ , v:=range wulin{ fmt.Println(v) } }
如果想按照名字或者登记排序,修改
func (ws Wudangslice) Less(i,j int) bool { return ws[i].Name < ws[j].Name }