go语言结构体对象按照时间对象排序
程序员文章站
2022-07-07 15:12:50
...
获取用户列表,按照申请时间倒序排序,注:调用标准库的sort.Sort必须要先实现Len(),Less(),Swap() 三个方法.
......
import (
"fmt"
"io/ioutil"
"sort"
"time"
)
type User struct {
ApplicantGuid string `json:"applicant_guid"`
ApplyTime string `json:"apply_time"`
UsedLicense int `json:"used_license"`
Applicant string `json:"applicant"`
}
type newUserList []User
func (I newUserList) Len() int {
return len(I)
}
func (I newUserList) Less(i, j int) bool {
return stringConvertTime(I[i].ApplyTime) > stringConvertTime(I[j].ApplyTime)
}
func (I newUserList) Swap(i, j int) {
I[i], I[j] = I[j], I[i]
}
例如对user_list进行排序:
TestData["license_detail"] = `{
"user_list":[
{
"applicant_guid":"guid",
"apply_time":"2018-03-06 20:44:51",
"used_license":"10",
"applicant":"tim1"
},
{
"applicant_guid":"guid11",
"apply_time":"2018-03-07 20:44:33",
"used_license":"10",
"applicant":"tim2"
},
{
"applicant_guid":"guid_tin",
"apply_time":"2018-03-05 20:44:33",
"used_license":"10",
"applicant":"tim3"
}
]
}`
var users []User
遍历user_list获取到users
sort.Sort(newUserList(users))进行排序可以得到正确排序
......
import (
"fmt"
"io/ioutil"
"sort"
"time"
)
type User struct {
ApplicantGuid string `json:"applicant_guid"`
ApplyTime string `json:"apply_time"`
UsedLicense int `json:"used_license"`
Applicant string `json:"applicant"`
}
type newUserList []User
func (I newUserList) Len() int {
return len(I)
}
func (I newUserList) Less(i, j int) bool {
return stringConvertTime(I[i].ApplyTime) > stringConvertTime(I[j].ApplyTime)
}
func (I newUserList) Swap(i, j int) {
I[i], I[j] = I[j], I[i]
}
例如对user_list进行排序:
TestData["license_detail"] = `{
"user_list":[
{
"applicant_guid":"guid",
"apply_time":"2018-03-06 20:44:51",
"used_license":"10",
"applicant":"tim1"
},
{
"applicant_guid":"guid11",
"apply_time":"2018-03-07 20:44:33",
"used_license":"10",
"applicant":"tim2"
},
{
"applicant_guid":"guid_tin",
"apply_time":"2018-03-05 20:44:33",
"used_license":"10",
"applicant":"tim3"
}
]
}`
var users []User
遍历user_list获取到users
sort.Sort(newUserList(users))进行排序可以得到正确排序
推荐阅读