鉴于以下 struct
type 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 error
func (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 []Point
func (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
}
犯罪嫌疑人X
相关分类