gpt4 book ai didi

go - 按 createdDate golang 排序列表

转载 作者:数据小太阳 更新时间:2023-10-29 03:38:51 26 4
gpt4 key购买 nike

我有一个返回 Inspections 的模型实例的函数,我想按 CreatedDate 对它进行排序,但是在我编译之后我得到了

cannot use inspections[i].CreatedDate (type string) as type bool in return argument

inspection.go

type Inspection struct {
Id int64 `db:"id,omitempty" json:"id,omitempty"`
CreatedDate string `db:"created,omitempty" json:"created_date,omitempty"`
Records []*InspectionRecord `db:"-" json:"records,omitempty"`
InspectionFields
}

list.go

import (
"sort"
)

func (s *Manager) list(fields *inspection.ItemIdField) (*inspection.InspectionHistoryResponse, error) {
return s.listItemInspectionHistory(fields.ItemId)
}

func (s *Manager) listItemInspectionHistory(itemId string) (*inspection.InspectionHistoryResponse, error) {
g := config.Client.Inspections()

var inspections []*models.Inspection

inspections, err := g.FindInspections(itemId)

if err != nil {
s.Log.Debugf("Can't find inspections of item with id %s", itemId)
return nil, err
}
s.Log.Debugf("Found %d inspections for item with id %s", len(inspections), itemId)

for _, inspection := range inspections {
inspection.Records, err = g.FindRecords(inspection.Id)
if err != nil {
s.Log.Debugf("Can't find records for inspection with id %d", inspection.Id)
return nil, err
}
s.Log.Debugf("Found %d records for inspection with id %d", len(inspection.Records), inspection.Id)
}

model := new(models.InspectionHistory)
model.Inspections = inspections
// sort by CreatedDate
sort.Slice(inspections, func(i, j int) bool { return inspections[i].CreatedDate })

return transform.InspectionHistoryModelToProtobufResponse(model)
}

错误很明显,但我对如何解决它有点困惑,有人可以向我解释如何解决这个问题吗?谢谢。

最佳答案

您必须解析日期字符串并将它们与 time.Time 进行比较实例

假设您有一个有效的日期并且他们在 RFC3339 ,您可以执行以下操作

    sort.Slice(inspections, func(i, j int) bool {
t1, _ := time.Parse(time.RFC3339, inspections[i].CreatedDate)
t2, _ := time.Parse(time.RFC3339, inspections[j].CreatedDate)
return t1.After(t2)
})

关于go - 按 createdDate golang 排序列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55477464/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com