LoginSignup
3
2

More than 1 year has passed since last update.

【Golang】sort.Sliceでtime.Time型のスライスをソート

Last updated at Posted at 2021-05-09

概要

time.Timeの型を持ったstructのスライスをソートする方法
sort interfaceを満たすメソッド(Len, Less, Swapメソッド)を用意する方法よりこちらの方が簡単なので、メモ

実装

package main

import (
    "fmt"
    "time"
    "sort"
)

type User struct {
    Name      string
    CreatedAt time.Time
}

func main() {
    us := []User{
        {
            Name:      "john",
            CreatedAt: time.Now().Add(time.Minute),
        },
        {
            Name:      "kenta",
            CreatedAt: time.Now(),
        },
    }
    fmt.Println(us)
    sort.Slice(us, func(i, j int) bool {
        return us[i].CreatedAt.Before(us[j].CreatedAt)
    })
    fmt.Println(us)
}
// Sort前
// [{john 2009-11-10 23:01:00 +0000 UTC m=+60.000000001} {kenta 2009-11-10 23:00:00 +0000 UTC m=+0.000000001}]
// Sort後
// [{kenta 2009-11-10 23:00:00 +0000 UTC m=+0.000000001} {john 2009-11-10 23:01:00 +0000 UTC m=+60.000000001}]
3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2