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,它接受一个切片和一个比较函数。
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}]
对于更复杂的排序逻辑,可以为类型实现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]
这种方法适合需要复用排序规则或多字段组合排序的场景。
基本上就这些。以上就是Golang sort切片排序与自定义排序示例的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号