概述

golang的sort包默认支持int, float64, string的从小大到排序:

int -> Ints(x []int)
float64 -> Float64s(x []float64)
string -> Strings(x []string)

同时它还提供了自定义的排序接口Interface,此接口保护三个方法。

golang默认提供了三个类型,他们都实现了Interface:
Float64Slice
IntSlice
StringSlice

从大到小排序

方法1:先使用提供的从大到小排序,再翻转

方法二:自定义类型实现

按照结构体的某个字段排序

按年纪从大到小排序

打印

[{20 12} {11 12} {10 12} {10 12} {9 12}]

按年纪从大到小,如果年纪相等的,按身高从小到到

打印

[{20 12} {10 11} {10 100} {10 110} {10 120}]

使用 sort.Stable 进行稳定排序

sort.Sort 并不保证排序的稳定性。如果有需要, 可以使用 sort.Stable ,用法就是将sort.Sort 替换为 sort.Stable

附:go根据结构体中任意字段进行排序

附:根据结构体中任意字段进行排序

Sort()

Reverse()

Less(i,j int) bool

Len() int

Swap(i,j int)

总结