Golang的sort使用总结

标准方法

golang的sort在封装之后还挺好用的,但是封装略微有点繁琐。

首先需要被排序的数组声明一个别名:

type Test struct {
	Math    int
	Chinese int
}

type StuScores []Test

然后需要该类型实现三个方法:

func (s StuScores) Len() int
func (s StuScores) Swap(i, j int)
func (s StuScores) Less(i, j int) bool 

实现完毕后就可以使用以下的方法进行排序操作:

sort.Sort(s) //正序
sort.Sort(sort.Reverse(s)) //逆序

此外还能自动实现以下的方法:

sort.IsSorted(s) //返回是否已经有序的bool

给出我一的一个例子:
实现按照chinese排序

type Test struct {
	Math    int
	Chinese int
}

type StuScores []Test

func (s StuScores) Len() int {
	return len(s)
}

func (s StuScores) Swap(i, j int) {
	s[i], s[j] = s[j], s[i]
}

func (s StuScores) Less(i, j int) bool {
	return s[i].Chinese < s[j].Chinese
}

func main() {
	s := StuScores{Test{Math: 12, Chinese: 22}, Test{Math: 42, Chinese: 41}, Test{Math: 532, Chinese: 53}}
	for _, v := range s {
		fmt.Println(v.Chinese, v.Math)
	}
	sort.Sort(s)
	fmt.Println()
	for _, v := range s {
		fmt.Println(v.Chinese, v.Math)
	}

	fmt.Println("is sort ?", sort.IsSorted(s))
	sort.Sort(sort.Reverse(s))
	for _, v := range s {
		fmt.Println(v.Chinese, v.Math)
	}
}

快速定义法

使用sort.Silce方法可以快速指定比较函数,类似于C++的结构体排序,emmm、、、感觉这才是正确的打开方式:
下面实现的是按照分数(Score)的降序排序效果:

package main

import (
	"fmt"
	"sort"
)

type Student struct {
	Name  string
	Score int
	ID    int
}

func main() {
	stuList := make([]Student, 0, 4)
	stuList = append(stuList, []Student{
		{
			ID:    1,
			Score: 23,
			Name:  "Tome",
		},
		{
			ID:    5,
			Score: 88,
			Name:  "Smile",
		},
		{
			ID:    2,
			Score: 99,
			Name:  "FFOl",
		},
		{
			ID:    3,
			Score: 33,
			Name:  "LOP",
		},
	}...)

	sort.Slice(stuList, func(i, j int) bool {
		return stuList[i].Score > stuList[j].Score
	})

	fmt.Println(stuList)

}

输出:

[{FFOl 99 2} {Smile 88 5} {LOP 33 3} {Tome 23 1}]
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值