golang结构体sort排序

package main

import (
"fmt"
"math/rand"
"sort"
"strconv"
)

func main() {
oneArr := make([]*One, 10)
for i := 0; i < 10; i++ {
oneArr[i] = &One{
Name: "name" + strconv.FormatInt(int64(i), 10),
Num: rand.Intn(1000),
}
}

sort.Sort(OneList(oneArr))
for _, v := range oneArr {
fmt.Print(v, " ")
}

}

type One struct {
Num int
Name string
}

type OneList []*One

func (this OneList) Len() int {
return len(this)
}
func (this OneList) Less(i, j int) bool {
return this[i].Num < this[j].Num
}
func (this OneList) Swap(i, j int) {
this[i], this[j] = this[j], this[i]
}

posted on 2022-03-25 14:06  studyphp  阅读(232)  评论(0编辑  收藏  举报

导航