Home >Backend Development >Golang >How to Correctly Sort Structs Containing `time.Time` Fields in Go?
Sorting Structs by Time.Time in Go
Sorting structs based on member fields of type time.Time can be a common task in Go programming. To understand the solution, let's delve into the problem:
Problem:
When attempting to sort a struct with a time.Time member called date, using custom sorting functions, the resulting list remains unsorted.
Custom Sorting Functions:
You provided the following custom sorting functions:
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] }
These functions define a custom type timeSlice that implements the sort.Interface interface, required for sorting in Go.
Map Sorting:
You aimed to sort a map of type map[string]reviews_data by the date field of its values. Here's your sorting code:
//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)
Solution:
The problem arises from the incorrect call to sort.Sort. For Go versions 1.8 and above, the recommended way to sort a slice is using sort.Slice:
sort.Slice(date_sorted_reviews, func(i, j int) bool { return date_sorted_reviews[i].date.Before(date_sorted_reviews[j].date) })
This syntax explicitly defines the slice to be sorted and the sorting function. Using this updated code will correctly sort your structs by their date field.
The above is the detailed content of How to Correctly Sort Structs Containing `time.Time` Fields in Go?. For more information, please follow other related articles on the PHP Chinese website!