结构/结果的反向时间顺序



才开始学习Golang。

想知道我们如何在GO中以相反的顺序对结构元素进行排序。假设,我从数据库中获得了类似的结果:

var results []<someClass>
collection.C(results).Find(bson.M{"<someid>":<id_val>}).All(&results)

现在,我的数据库对象/结果在slice results中可用。如何在称为时间的列上以相反顺序对切片results进行排序?

最简单的是让mongodb对记录进行排序:

var results []YourType
err := sess.DB("").C("collname").Find(bson.M{"someid": "someidval"}).
    Sort("-timefield").All(&results)

由于某种原因,您不能或不想这样做,则可以使用sort软件包。您需要实现sort.Interface

例如:

type YourType struct {
    SomeId    string
    Timestamp time.Time
}
type ByTimestamp []YourType
func (a ByTimestamp) Len() int           { return len(a) }
func (a ByTimestamp) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByTimestamp) Less(i, j int) bool {
    return a[i].Timestamp.After(a[j].Timestamp)
}

ByTimestamp类型是YourType的切片,它定义了反向时间戳订单,因为Less()方法使用Time.After()来决定元素和索引i是否小于index j的元素。

并使用它(在Go Playground上尝试):

var results []YourType
// Run your MongoDB query here
// Now sort it by Timestamp decreasing:
sort.Sort(ByTimestamp(results))

Less()的替代实现是使用Time.Before(),但在索引j上比较元素与索引i

func (a ByTimestamp) Less(i, j int) bool {
    return a[j].Timestamp.Before(a[i].Timestamp)
}

在Go操场上尝试此变体。

最新更新