这个答案在这里按时间排序。在戈朗的时间
尝试使用带有映射的辅助数组进行排序
type timeSlice []reviews_data
是否可以在不创建此辅助数据结构的情况下对带有日期的对象进行排序?
给定一个结构,例如
type SortDateExample struct {
sortByThis time.Time
id string
}
一个切片初始化了类似的东西
var datearray = var alerts = make([]SortDateExample, 0)
dateSlice = append(dateSlice,newSortDateExmple)
dateSlice = append(dateSlice,newSortDateExmple2)
dateSlice = append(dateSlice,newSortDateExmple3)
如何按时间字段排序数组 sortByThis?
使用 Go 1.8 及以上
版本sort.Slice(dateSlice, func(i, j int) bool {
return dateSlice[i].sortByThis.Before(dateSlice[j].sortByThis)
})
https://golang.org/pkg/sort/#Slice
Go 低于 1.8
在这种情况下,您不需要 map
,但您确实需要为数组定义一个类型:
type SortedDateExampleArray []SortDateExample
然后,您需要该数组类型来实现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]
}
然后,您可以使用sort.Sort
对自定义数组进行排序。
https://golang.org/pkg/sort/#Sort