Last active
August 14, 2020 10:55
-
-
Save zono-dev/377e5d76d335f73eb662ffc6dc02a09e to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "fmt" | |
| "sort" | |
| "time" | |
| ) | |
| type FileInfo struct { | |
| FileName string | |
| CreatedAt time.Time | |
| } | |
| func s_print(s []FileInfo, title string) { | |
| fmt.Println(title) | |
| for i, v := range s { | |
| fmt.Printf("%d: %s, %s\n", i, v.FileName, v.CreatedAt.Format(time.RFC3339)) | |
| } | |
| } | |
| func main() { | |
| s := []FileInfo{ | |
| {"file_middle", time.Now().Add(12 * time.Hour)}, | |
| {"file_first", time.Now()}, | |
| {"file_last", time.Now().Add(24 * time.Hour)}, | |
| } | |
| s_print(s, "Before") | |
| // Before | |
| // 0: file_middle, 2020-08-09T01:25:46Z | |
| // 1: file_first, 2020-08-08T13:25:46Z | |
| // 2: file_last, 2020-08-09T13:25:46Z | |
| // sort by newest to oldest | |
| sort.Slice(s, func(i, j int) bool { | |
| return s[i].CreatedAt.After(s[j].CreatedAt) | |
| }) | |
| s_print(s, "Sort by newest to oldest") | |
| // Sort by newest to oldest | |
| // 0: file_last, 2020-08-09T13:25:46Z | |
| // 1: file_middle, 2020-08-09T01:25:46Z | |
| // 2: file_first, 2020-08-08T13:25:46Z | |
| // sort by oldest to newest | |
| sort.Slice(s, func(i, j int) bool { | |
| return s[i].CreatedAt.Before(s[j].CreatedAt) | |
| }) | |
| s_print(s, "Sort by oldest to newest") | |
| // Sort by oldest to newest | |
| // 0: file_first, 2020-08-08T13:25:46Z | |
| // 1: file_middle, 2020-08-09T01:25:46Z | |
| // 2: file_last, 2020-08-09T13:25:46Z | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment