golang_切片排序:使用sort.Slice进行切片的排序
程序员文章站
2024-03-01 13:21:46
...
package main
import (
"fmt"
"sort"
)
type MyStruct struct {
ID int
Name string
Time string
}
func main() {
my := []MyStruct{
{1, "eric", "2021-07-20T17:24:48.56383Z"},
{3, "lucy", "2021-07-10T17:24:48.56383Z"},
{2, "yoly", "2021-07-30T17:24:48.56383Z"},
}
sort.Slice(my, func(i, j int) bool {
return my[i].Time < my[j].Time
})
fmt.Println("my:", my)
}
Output:
my: [{3 lucy 2021-07-10T17:24:48.56383Z} {1 eric 2021-07-20T17:24:48.56383Z} {2 yoly 2021-07-30T17:24:48.56383Z}]
按字段Time从小到大进行排序