在 go 1.2 中按时间日期字段对结构切片进行排序,无需创建二级结构

cam*_*car 0 sorting time go

这个答案在这里按时间排序。Golang 时间

尝试使用带有地图的辅助数组进行排序

type timeSlice []reviews_data
Run Code Online (Sandbox Code Playgroud)

可以在不创建此辅助数据结构的情况下对带有日期的对象的 golang 切片进行排序吗?

给定一个像这样的结构

type SortDateExample struct {
    sortByThis time.Time
    id string
}    
Run Code Online (Sandbox Code Playgroud)

一个切片初始化了类似的东西

var datearray = var alerts = make([]SortDateExample, 0)
dateSlice = append(dateSlice,newSortDateExmple)
dateSlice = append(dateSlice,newSortDateExmple2)
dateSlice = append(dateSlice,newSortDateExmple3)
Run Code Online (Sandbox Code Playgroud)

如何按时间字段 sortByThis 对数组进行排序?

eug*_*ioy 8

使用 Go 1.8 及以上版本

sort.Slice(dateSlice, func(i, j int) bool { 
    return dateSlice[i].sortByThis.Before(dateSlice[j].sortByThis) 
})
Run Code Online (Sandbox Code Playgroud)

https://golang.org/pkg/sort/#Slice

Go 版本低于 1.8

在这种情况下,您不需要 a map,但您确实需要为数组定义一个类型:

type SortedDateExampleArray []SortDateExample
Run Code Online (Sandbox Code Playgroud)

然后您需要该数组类型来实现 中的方法sort.Interface。

func (a SortedDateExampleArray) Len() int {
    return len(a)
}

func (a SortedDateExampleArray) Less(i, j int) bool {
    return a[i].sortByThis.Before(a[j].sortByThis)
}

func (a SortedDateExampleArray) Swap(i, j int) {
    a[i], a[j] = a[j], a[i]
}
Run Code Online (Sandbox Code Playgroud)

然后您可以使用sort.Sort它对自定义数组进行排序。

https://golang.org/pkg/sort/#Sort