golang结构体slice排序方式
作者:YZF_Kevin
go语言的slice()不仅可以对int类型的数组进行排序,还可以对struct类型的数组进行排序,排序函数包括Slice()、SliceStable()和SliceIsSorted(),结构体可以定义为更复杂的类型
golang结构体slice排序
go语言的slice()不仅仅可以对int类型的数组进行排序,还可以对struct类型的数组进行排序
排序函数
- 1. Slice() 不稳定排序
- 2. SliceStable() 稳定排序
- 3. SliceIsSorted() 判断是否已排序
结构体定义如下,我们完全可以定义更复杂的结构体:
// 结构体定义
type test struct {
value int
str string
}结果

完整代码
package main
import (
"fmt"
"sort"
)
// 结构体定义
type test struct {
value int
str string
}
func main() {
s := make([]test, 5)
s[0] = test{value: 2, str: "test2"}
s[1] = test{value: 4, str: "test4"}
s[2] = test{value: 1, str: "test1"}
s[3] = test{value: 5, str: "test5"}
s[4] = test{value: 3, str: "test3"}
fmt.Println("初始化结果:")
fmt.Println(s)
// 从小到大排序(不稳定排序)
sort.Slice(s, func(i, j int) bool {
if s[i].value < s[j].value {
return true
}
return false
})
fmt.Println("\n从小到大排序结果:")
fmt.Println(s)
// 从小到大排序(稳定排序)
sort.SliceStable(s, func(i, j int) bool {
if s[i].value < s[j].value {
return true
}
return false
})
// 是否从小到大排序
bLess := sort.SliceIsSorted(s, func(i, j int) bool {
if s[i].value < s[j].value {
return true
}
return false
})
fmt.Printf("数组s是否从小到大排序,bLess:%v\n", bLess)
// 从大到小排序(不稳定排序)
sort.Slice(s, func(i, j int) bool {
if s[i].value > s[j].value {
return true
}
return false
})
fmt.Println("\n从大到小排序结果:")
fmt.Println(s)
// 是否从大到小排序
bMore := sort.SliceIsSorted(s, func(i, j int) bool {
if s[i].value > s[j].value {
return true
}
return false
})
fmt.Printf("数组s是否从大到小排序,bMore:%v\n", bMore)
}总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
