go语言中sort包支持切片排序,提供sort.ints等基础函数、sort.Slice自定义排序及实现sort.Interface接口三种方式,满足升序、降序和稳定排序等需求。

在Go语言中,sort 包提供了对切片和数组进行排序的高效方法。虽然Go不支持直接对数组排序(因为数组大小固定且传参时是值传递),但通过 sort 包可以轻松处理切片,而切片正是操作数组的主要方式。掌握 sort 的使用,能让你快速实现升序、降序、自定义排序等常见需求。
基本类型切片排序
对于常见的基本类型如 int、float64、String,sort 包提供了专用函数:
这些函数会直接修改原切片,无需返回新切片。
示例:
ints := []int{3, 1, 4, 1, 5} sort.Ints(ints) fmt.Println(ints) // 输出: [1 1 3 4 5] strs := []string{"banana", "apple", "cherry"} sort.Strings(strs) fmt.Println(strs) // 输出: [apple banana cherry]
自定义排序:使用 sort.Slice()
当元素是结构体或需要按特定规则排序时,可使用 sort.Slice(),它接受一个比较函数 func(i, j int) bool,当 i 应排在 j 前面时返回 true。
立即学习“go语言免费学习笔记(深入)”;
比如按学生分数从高到低排序:
type Student struct { Name string Score int } students := []Student{ {"Alice", 85}, {"Bob", 92}, {"Charlie", 78}, } sort.Slice(students, func(i, j int) bool { return students[i].Score > students[j].Score // 降序 }) // 结果: Bob(92), Alice(85), Charlie(78)
若想按姓名字母顺序升序,改为:return students[i].Name 。
实现 sort.Interface 自定义类型
对于频繁使用的自定义类型,可以实现 sort.Interface 接口,包含 len()、less(i, j)、Swap(i, j) 三个方法。
继续以 Student 为例:
type ByScore []Student func (a ByScore) Len() int { return len(a) } func (a ByScore) Swap(i, j int) { a[i], a[j] = a[j], a[i] } func (a ByScore) Less(i, j int) bool { return a[i].Score < a[j].Score } // 使用 sort.Sort(ByScore(students))
这种方式适合需要复用排序逻辑的场景,代码更清晰。
反向排序与稳定排序
如果要对已有规则取反,比如升序变降序,可用 sort.Reverse() 包装:
sort.Sort(sort.Reverse(ByScore(students))) // 按分数降序
而 sort.Stable() 保证相等元素的相对顺序不变,适用于需要保持原始顺序的稳定排序场景。
基本上就这些。掌握 sort.Ints、sort.Slice 和自定义 sort.Interface,就能应对大多数排序需求。实际开发中,sort.Slice 因其简洁性最常用,尤其适合一次性排序逻辑。理解这些方法后,golang 中的排序就不再复杂了。