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