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

报告相同问题?

悬赏问题

  • ¥50 寻找一位有逆向游戏盾sdk 应用程序经验的技术
  • ¥15 请问有用MZmine处理 “Waters SYNAPT G2-Si QTOF质谱仪在MSE模式下采集的非靶向数据” 的分析教程吗
  • ¥50 opencv4nodejs 如何安装
  • ¥15 adb push异常 adb: error: 1409-byte write failed: Invalid argument
  • ¥15 nginx反向代理获取ip,java获取真实ip
  • ¥15 eda:门禁系统设计
  • ¥50 如何使用js去调用vscode-js-debugger的方法去调试网页
  • ¥15 376.1电表主站通信协议下发指令全被否认问题
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥15 复杂网络,变滞后传递熵,FDA