鉴于以下 structtype Point struct { datetimeRecorded time.Time}// Returns true if the point was recorded before the comparison point.// If datetime is not available return false and an errorfunc (p1 Point) RecordedBefore(p2 Point) (isBefore bool, err error) { if (p1.datetimeRecorded.IsZero()) || (p2.datetimeRecorded.IsZero()) { err = ErrNoDatetime } else { isBefore = p1.datetimeRecorded.Before(p2.datetimeRecorded) } return}我想[]Point按datetimeRecorded属性对 a 进行排序。我有以下(有效):type ByDatetimeRecorded []Pointfunc (a ByDatetimeRecorded) Len() int { return len(a)}func (a ByDatetimeRecorded) Swap(i, j int) { a[i], a[j] = a[j], a[i]}func (a ByDatetimeRecorded) Less(i, j int) bool { swap, _ := a[i].RecordedBefore(a[j]) return swap}但是,如果datetimeRecorded在任一比较中都未初始化该属性,error则将被捕获并且不会交换点(返回false)。是否可以捕获此错误并将其从数组中删除?类似的东西:func (a ByDatetimeRecorded) Less(i, j int) bool { swap, err := a[i].RecordedBefore(a[j]) if err != nil { // Remove element here } return swap}编辑 1我可能必须更具体地说明要删除的元素,因此这可能更有意义:func (a ByDatetimeRecorded) Less(i, j int) bool { if a[i].datetimeRecorded.IsZero() { // Drop a[i] } if a[j].datetimeRecorded.IsZero() { // Drop a[j] } swap, _ := a[i].RecordedBefore(a[j]) return swap}
1 回答
犯罪嫌疑人X
TA贡献2080条经验 获得超4个赞
标准排序包不会从切片中删除元素。在排序之前过滤掉切片中的零值。
i := 0
for _, p := range points {
if !p.datetimeRecorded.IsZero() {
points[i] = p
i++
}
}
points = points[:i]
sort.Sort(ByDatetimeRecorded(points))
- 1 回答
- 0 关注
- 203 浏览
添加回答
举报
0/150
提交
取消