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 {

Id int64

Date time.Time

Title string

Content string

}



posts := []Post{p1, p2, p3, p4}

sort array in Go

Len

Swap

Less

Less

type ByDate []Post



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))

There is a chance that you will also have a container for those Posts in your code.Now, how can you sort this array by dates? If you search foryou will get as first result the sort package with some great examples. Sorting by atype is not different, all you need is to change the sort implementation for Time type.So for this specific example we need to implementand. For thefunction, use the Before function available in thepackage.Finally, just call the sort function:I made a Gist sortbydate.go with a simple example, an array of dates, and as you can see this is easily extendable.