Recently I had to order an array of structures based on a time.Time field. Doing this was surprisingly easy in Go, so much that it is worth a small post :-)
Imagine you have a structure that contains a Date field, let’s use a simple Post structure as an example:
type Post struct {There is a chance that you will also have a container for those Posts in your code.
Id int64
Date time.Time
Title string
Content string
}
posts := []Post{p1, p2, p3, p4}Now, how can you sort this array by dates? If you search for
sort array in Go
you will get as first result the sort package with some great examples. Sorting by a time.Time type is not different, all you need is to change the sort implementation for Time type.Len
, Swap
and Less
. For the Less
function, use the Before function available in the time package.type ByDate []PostFinally, just call the sort function:
func (a ByDate) Len() int { return len(a) }
func (a ByDate) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByDate) Less(i, j int) bool { return a[i].Date.Before(a[j].Date) }
sort.Sort(ByDate(posts))I made a Gist sortbydate.go with a simple example, an array of dates, and as you can see this is easily extendable.