golang对struct排序的方法
以下代码示例,通过对Student 结构体的age字段进行从小到大和从大到小排序
方法一
使用 sort.Slice() 进行排序
package main
import (
"fmt"
"sort"
)
type Student struct {
name string
age int
}
func main() {
students := []Student{
{name: "tom", age: 18},
{name: "jack", age: 20},
{name: "steve", age: 19},
}
// 1、排序前
fmt.Println(students)
// [{tom 18} {jack 20} {steve 19}]
// 2、由小到大排序
sort.Slice(students, func(i, j int) bool {
return students[i].age < students[j].age
})
fmt.Println(students)
// [{tom 18} {steve 19} {jack 20}]
// 3、由大到小排序
sort.Slice(students, func(i, j int) bool {
return students[j].age < students[i].age
})
fmt.Println(students)
// [{jack 20} {steve 19} {tom 18}]
}
方法二
使用sort.Sort() 进行排序
使用sort.Sort() 方法需要重写Len()、Swap()、Less() 这三个方法
package main
import (
"fmt"
"sort"
)
type Student struct {
name string
age int
}
type Students []Student
func (a Students) Len() int {
return len(a)
}
func (a Students) Swap(i, j int) {
a[i], a[j] = a[j], a[i]
}
func (a Students) Less(i, j int) bool {
return a[i].age < a[j].age
}
func main() {
students := []Student{
{name: "tom", age: 18},
{name: "jack", age: 20},
{name: "steve", age: 19},
}
// 1、排序前
fmt.Println(students)
// [{tom 18} {jack 20} {steve 19}]
// 2、由小到大排序
sort.Sort(Students(students))
fmt.Println(students)
// [{tom 18} {steve 19} {jack 20}]
// 3、由大到小 排序
sort.Sort(sort.Reverse(Students(students)))
fmt.Println(students)
// [{jack 20} {steve 19} {tom 18}]
}