答案是使用sort包可对Go语言切片进行排序,基本类型可用专用函数如sort.Ints、sort.Strings,结构体排序推荐用sort.Slice并提供比较函数。

在Go语言中,sort 包提供了对切片和用户自定义数据结构进行排序的实用功能。使用 sort 对切片排序非常直接,主要根据元素类型选择对应的方法。
对基本类型切片排序
对于常见类型如 int、float64、string 的切片,sort 包提供了专用函数:
- sort.Ints([]int):对整型切片升序排序
- sort.Float64s([]float64):对 float64 切片排序
- sort.Strings([]string):对字符串切片按字典序排序
示例:
ints := []int{5, 2, 8, 1}
sort.Ints(ints)
fmt.Println(ints) // 输出: [1 2 5 8]
strs := []string{"banana", "apple", "cherry"}
sort.Strings(strs)
fmt.Println(strs) // 输出: [apple banana cherry]
降序排序
如果需要降序排列,可以使用 sort.Sort 配合 sort.Reverse:
立即学习“go语言免费学习笔记(深入)”;
sort.Sort(sort.Reverse(sort.IntSlice(ints))) fmt.Println(ints) // 降序输出: [8 5 2 1]
其中 sort.IntSlice 是实现了 sort.Interface 的类型,包装了 []int。
对结构体或自定义类型排序
当切片元素是结构体时,需实现 sort.Interface 接口(Len, Less, Swap),或使用 sort.Slice 提供匿名比较函数。
推荐使用 sort.Slice,更简洁:
type Person struct {
Name string
Age int
}
people := []Person{
{"Alice", 30},
{"Bob", 25},
{"Carol", 35},
}
// 按年龄升序
sort.Slice(people, func(i, j int) bool {
return people[i].Age < people[j].Age
})
也可按名字排序:
sort.Slice(people, func(i, j int) bool {
return people[i].Name < people[j].Name
})
总结常用方法
- 基本类型:用 sort.Ints、sort.Strings 等
- 降序:结合 sort.Reverse 和对应 Slice 类型
- 结构体排序:优先使用 sort.Slice + lambda 函数
- 复杂逻辑:可实现 sort.Interface 自定义类型
基本上就这些。Go 的排序设计简洁高效,日常开发中 sort.Slice 能解决大多数需求。注意排序是原地操作,会修改原切片。不复杂但容易忽略细节,比如比较函数返回值决定顺序。










