我试图通过其成员类型time.Time在GOlang中对结构进行排序。 结构如下。
type reviews_data struct {
review_id string
date time.Time
score int
firstname string
anonymous bool
review_text string
title_text string
rating float64
upcount int
}
我有以下功能进行排序
type timeSlice []reviews_data
// Forward request for length
func (p timeSlice) Len() int {
return len(p)
}
// Define compare
func (p timeSlice) Less(i, j int) bool {
return p[i].date.Before(p[j].date)
}
// Define swap over an array
func (p timeSlice) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}
地图定义如下
var reviews_data_map = make(map[string]reviews_data)
在地图填充值后,按值对地图进行排序
//Sort the map by date
date_sorted_reviews := make(timeSlice, 0, len(reviews_data_map))
for _, d := range reviews_data_map {
date_sorted_reviews = append(date_sorted_reviews, d)
}
sort.Sort(date_sorted_reviews)
问题是结果没有排序。任何人都可以告诉我问题是什么。 提前谢谢。
答案 0 :(得分:25)
它看起来像我一样:
package main
import (
"fmt"
"sort"
"time"
)
type reviews_data struct {
review_id string
date time.Time
score int
firstname string
anonymous bool
review_text string
title_text string
rating float64
upcount int
}
type timeSlice []reviews_data
func (p timeSlice) Len() int {
return len(p)
}
func (p timeSlice) Less(i, j int) bool {
return p[i].date.Before(p[j].date)
}
func (p timeSlice) Swap(i, j int) {
p[i], p[j] = p[j], p[i]
}
func main() {
var reviews_data_map = make(map[string]reviews_data)
reviews_data_map["1"] = reviews_data{date: time.Now().Add(12 * time.Hour)}
reviews_data_map["2"] = reviews_data{date: time.Now()}
reviews_data_map["3"] = reviews_data{date: time.Now().Add(24 * time.Hour)}
//Sort the map by date
date_sorted_reviews := make(timeSlice, 0, len(reviews_data_map))
for _, d := range reviews_data_map {
date_sorted_reviews = append(date_sorted_reviews, d)
}
fmt.Println(date_sorted_reviews)
sort.Sort(date_sorted_reviews)
fmt.Println(date_sorted_reviews)
}
输出:
[{ {63393534000 0 0x1ba3e0} 0 false 0 0} { {63393490800 0 0x1ba3e0} 0 false 0 0} { {63393577200 0 0x1ba3e0} 0 false 0 0}]
[{ {63393490800 0 0x1ba3e0} 0 false 0 0} { {63393534000 0 0x1ba3e0} 0 false 0 0} { {63393577200 0 0x1ba3e0} 0 false 0 0}]
答案 1 :(得分:20)
GO 1.8或以上:
sort.Slice(timeSlice, func(i, j int) bool { return timeSlice[i].date.Before(timeSlice[j].date)})
答案 2 :(得分:0)
这可以在下面的版本1.8中完成,而无需多余的类型和对应的答案。
package main
import (
"fmt"
"time"
"sort"
)
type reviews_data struct {
review_id string
date time.Time
}
func main() {
fmt.Println("Sort Example")
var listOfReviews = make([]reviews_data, 0)
listOfReviews = append(listOfReviews, reviews_data{review_id: "1",date:time.Now()})
listOfReviews = append(listOfReviews, reviews_data{review_id: "2",date: time.Now().AddDate(0, 0, 7*1)})
listOfReviews = append(listOfReviews, reviews_data{review_id: "1",date: time.Now().AddDate(0, 0, 7*-1)})
sort.Slice(listOfReviews, func(i, j int) bool { return listOfReviews[i].date.Before(listOfReviews[j].date) })
}