Goのsortパッケージでtime.Timeの要素を基にソートする
時間でソートしたい
小ネタ。
sort.Sliceでソート
Go1.8以降でならsort.Sliceを使ったシンプルな方法でソートできる。
Go 1.8 Release Notes - The Go Programming Language
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 | |
} |
Len,Swap,Lessを使う
Go1.8より前、もしくは独自のソートを行いたい場合はsort.Sortのinterfaceを満たすためにLen,Swap,Lessを用意する。