Home >Backend Development >Golang >How to Correctly Sort a Go Struct by its time.Time Field?
Sorting a Struct by Its time.Time Field
You're attempting to sort a struct in Go by its time.Time field, which has encountered a problem. The code fragment you provided includes a custom sort implementation using a slice of your reviews_data struct and a map:
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] }
However, your reported issue is that the result is not sorted correctly. This can be due to several reasons:
Improved Solution (Go 1.8 and above):
Using the sort.Slice function introduced in Go 1.8, you can simplify your sorting code:
sort.Slice(timeSlice, func(i, j int) bool { return timeSlice[i].date.Before(timeSlice[j].date) })
This improved solution uses the standard library's sorting functionality, ensuring a more reliable and efficient sorting process.
The above is the detailed content of How to Correctly Sort a Go Struct by its time.Time Field?. For more information, please follow other related articles on the PHP Chinese website!