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

在 Go 语言中,sort 包提供了对切片排序的多种方式,既支持内置类型的升序/降序,也支持通过自定义比较逻辑实现灵活排序。关键在于理解 sort.Slice 和 sort.Sort 的使用场景与区别。
sort.Slice 是最常用、最简洁的方式,适用于大多数自定义排序需求。它接受一个切片和一个匿名函数(比较函数),该函数接收两个索引 i 和 j,返回 true 表示 i 对应元素应排在 j 前面。
例如,对结构体切片按年龄升序、姓名降序排列:
type Person struct {
Name string
Age int
}
people := []Person{{"Alice", 30}, {"Bob", 25}, {"Charlie", 30}}
<p>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 接口(含 Len()、Less(i,j int) bool、Swap(i,j int) 三个方法)。
立即学习“go语言免费学习笔记(深入)”;
例如,定义一个按价格降序的 Products 类型:
type Product struct {
Name string
Price float64
}
type ByPrice []Product
<p>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] }</p><p>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
避免在比较函数中做耗时操作(如网络请求、文件读取),否则严重拖慢排序性能。
以上就是如何在Golang中使用sort对切片排序_自定义排序规则和比较函数的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号