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   studyphp  阅读(233)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

统计

点击右上角即可分享
微信分享提示