Go语言中sort包支持切片和自定义数据排序:对基本类型提供sort.Ints、sort.Float64s、sort.Strings等函数;复杂排序可使用sort.Slice配合比较函数,或实现Interface接口。

Go语言中的sort包提供了对切片和用户自定义数据结构进行排序的高效方法。对于基本类型的切片(如[]int、[]string),可以直接使用内置函数;而对于复杂结构或特定排序规则,则可通过自定义实现。
基本类型切片排序
对常见类型的切片排序,sort包提供了便捷函数:
-
sort.Ints():对[]int升序排序 -
sort.Float64s():对[]float64排序 -
sort.Strings():对[]string按字典序排序
package main
import (
"fmt"
"sort"
)
func main() {
nums := []int{5, 2, 8, 1}
sort.Ints(nums)
fmt.Println(nums) // 输出: [1 2 5 8]
words := []string{"banana", "apple", "cherry"}
sort.Strings(words)
fmt.Println(words) // 输出: [apple banana cherry]
}
使用sort.Slice进行自定义排序
当需要根据特定条件排序时,推荐使用sort.Slice,它接受一个切片和一个比较函数。
words := []string{"hi", "hello", "go", "world"}
sort.Slice(words, func(i, j int) bool {
return len(words[i]) < len(words[j])
})
fmt.Println(words) // 输出: [hi go hello world]
示例:结构体按字段排序
type Person struct {
Name string
Age int
}
people := []Person{
{"Alice", 30},
{"Bob", 25},
{"Charlie", 35},
}
// 按年龄升序
sort.Slice(people, func(i, j int) bool {
return people[i].Age < people[j].Age
})
fmt.Println(people)
// 输出: [{Bob 25} {Alice 30} {Charlie 35}]
实现Interface接口进行排序
对于更复杂的排序逻辑,可以为类型实现sort.Interface接口的三个方法:Len()、Less()、Swap()。
立即学习“go语言免费学习笔记(深入)”;
示例:逆序排序整数切片type IntDesc []int
func (a IntDesc) Len() int { return len(a) }
func (a IntDesc) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a IntDesc) Less(i, j int) bool { return a[i] > a[j] } // 降序
nums := []int{3, 1, 4, 2}
sort.Sort(IntDesc(nums))
fmt.Println(nums) // 输出: [4 3 2 1]
这种方法适合需要复用排序规则或多字段组合排序的场景。
基本上就这些。










