给定以下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进行排序。

我有以下内容(有效):
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
}

最佳答案

标准排序包不会从 slice 中删除元素。
排序前从 slice 中过滤出零值。

  i := 0
  for _, p := range points {
      if !p.datetimeRecorded.IsZero() {
         points[i] = p
         i++
      }
  }
  points = points[:i]
  sort.Sort(ByDatetimeRecorded(points))

10-06 13:45
查看更多