欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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从小到大进行排序