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 mainimport ( "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()。
青泥AI
青泥学术AI写作辅助平台
302 查看详情
立即学习“go语言免费学习笔记(深入)”;
示例:逆序排序整数切片
type IntDesc []intfunc (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切片排序与自定义排序示例的详细内容,更多请关注创想鸟其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/1148911.html
微信扫一扫
支付宝扫一扫