Sort slice of stuct (post) by its field

Hi All
i am trying to sort slice of struct post by its field created (time.Time)

finded answer after a break

sort.Slice(gPost, func(i, j int) bool { return gPost[i].Created.Hour() > gPost[j].Created.Hour() })

Just FYI your code only sorts based on the hour of the time, not the entire time. A better way to do this would be to use the Sub method that is on the time.Time type.

return gPost[i].Created.Sub(gPost[j].Created) < 0

If the first time is less than the second time then the resulting duration from a subtraction will be negative, otherwise it will be 0 or positive. You can see this more clearly here:

Thank you Jon.
thanks a lot.

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.