如何在Golang中使用sort对切片排序_自定义排序规则和比较函数

Go中排序有三种方式:sort.Slice适用于快速自定义排序;实现sort.Interface可复用排序逻辑;基本类型可用预置函数如sort.Ints。所有排序均原地修改切片。

在 Go 语言中,sort 包提供了对切片排序的多种方式,既支持内置类型的升序/降序,也支持通过自定义比较逻辑实现灵活排序。关键在于理解 sort.Slicesort.Sort 的使用场景与区别。

用 sort.Slice 实现快速自定义排序

sort.Slice 是最常用、最简洁的方式,适用于大多数自定义排序需求。它接受一个切片和一个匿名函数(比较函数),该函数接收两个索引 ij,返回 true 表示 i 对应元素应排在 j 前面。

例如,对结构体切片按年龄升序、姓名降序排列:

type Person struct {
    Name string
    Age  int
}
people := []Person{{"Alice", 30}, {"Bob", 25}, {"Charlie", 30}}

sort.Slice(people, func(i, j int) bool { if people[i].Age != people[j].Age { return people[i].Age < people[j].Age // 年龄升序 } return people[i].Name > people[j].Name // 同龄时姓名降序 })

实现 sort.Interface 以复用或封装排序逻辑

当需要多次使用同一排序规则,或想让类型“自带排序能力”时,可为类型实现 sort.Interface 接口(含 Len()Less(i,j int) boolSwap(i,j int) 三个方法)。

例如,定义一个按价格降序的 Products 类型:

type Product struct {
    Name  string
    Price float64
}
type ByPrice []Product

func (p ByPrice) Len() int { return len(p) } func (p ByPrice) Less(i, j int) bool { return p[i].Price > p[j].Price } func (p ByPrice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }

products := []Product{{"A", 99.9}, {"B", 19.5}} sort.Sort(ByPrice(products))

这样后续只需调用 sort.Sort(ByPrice(s)) 即可复用逻辑。

对基本类型切片使用预置函数

对于 []int[]string 等常见类型,sort 包已提供高效且语义清晰的函数:

  • sort.Ints(s []int) —— 升序
  • sort.Strings(s []string) —— 字典升序
  • sort.Float64s(s []float64) —— 升序(注意 NaN 处理)
  • 降序可用 sort.Sort(sort.Reverse(sort.IntSlice(s))) 或直接用 sort.Slice

例如字符串切片按长度降序:

words := []string{"go", "golang", "hi"}
sort.Slice(words, func(i, j int) bool {
    return len(words[i]) > len(words[j])
})

注意事项与常见陷阱

排序操作会**原地修改切片**,不产生新切片;若需保留原数据,请先复制。

比较函数必须满足严格弱序(strict weak ordering): - 不可同时有 Less(i,j)Less(j,i)true - 若 Less(i,j)Less(j,k)true,则 Less(i,k) 应为 true - Less(i,i) 必须为 false

避免在比较函数中做耗时操作(如网络请求、文件读取),否则严重拖慢排序性能。