go 结构体切片自定义排序

常见类型的默认排序实现

go sort包默认支持int(sort.Ints(x []int))、float64s(sort.Float64s(x []float64))、string(sort.Strings(x []string))从小到大排序,反序使用类似于sort.Sort(sort.Reverse(sort.Ints(x []int)))的方式。

结构体切片的自定义排序实现

package main
import (
"fmt"
"sort"
)
type Student struct {
Age int
Score int
}
type StudentSort []Student
func (s StudentSort) Len() int {
return len(s)
}
func (s StudentSort) Swap(i, j int) {
s[i], s[j] = s[j], s[i]
}
func (s StudentSort) Less(i, j int) bool {
return s[i].Score > s[j].Score
}
func main() {
s := []Student{
{Age:15, Score:1},
{Age:16, Score:0},
{Age:17, Score:30},
{Age:18, Score:50},
{Age:19, Score:40},
}
sort.Sort(StudentSort(s))
fmt.Printf("%+v", s)
}

posted on   王景迁  阅读(37)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· 分享一个免费、快速、无限量使用的满血 DeepSeek R1 模型,支持深度思考和联网搜索!
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· ollama系列1:轻松3步本地部署deepseek,普通电脑可用
· 按钮权限的设计及实现
· 25岁的心里话
< 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

导航

统计

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