duanpie4763 2019-04-02 14:40
浏览 34
已采纳

按createdDate golang排序列表

I have a function which returns model instance of Inspections and I want to sort it by CreatedDate but after I compile I've got

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

the inspection.go is

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
}

and the list.go is

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)
}

The error is obvious but I'm a bit confused on how to resolve it, can someone please explain to me how to resolve this? thanks.

  • 写回答

1条回答 默认 最新

  • dongxu4580 2019-04-02 14:50
    关注

    You have to parse the Date strings and compare them as time.Time instances

    Assuming you have a valid date and they are on RFC3339, you may do the following

        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)
        })
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序 用oss下载 aliyun-oss-sdk-6.18.0.min client报错
  • ¥15 ArcGIS批量裁剪
  • ¥15 labview程序设计
  • ¥15 为什么在配置Linux系统的时候执行脚本总是出现E: Failed to fetch http:L/cn.archive.ubuntu.com
  • ¥15 Cloudreve保存用户组存储空间大小时报错
  • ¥15 伪标签为什么不能作为弱监督语义分割的结果?
  • ¥15 编一个判断一个区间范围内的数字的个位数的立方和是否等于其本身的程序在输入第1组数据后卡住了(语言-c语言)
  • ¥15 Mac版Fiddler Everywhere4.0.1提示强制更新
  • ¥15 android 集成sentry上报时报错。
  • ¥15 抖音看过的视频,缓存在哪个文件