结构/结果的倒序排列

Just started learning goLang.

Wondering how can we sort an struct elements in reverse order in Go. Let's say, I am getting the results from database something like as:

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

Now, I have my database objects/results available in slice results. How can I sort the slice results in reverse order on a column called time?

Easiest would be to let MongoDB sort the records:

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

If for some reason you can't or don't want to do this, you may utilize the sort package. You need to implement sort.Interface.

For example:

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

This ByTimestamp type is a slice of YourType, and it defines a reverse timestamp order because the Less() method uses Time.After() to decide if element and index i is less than element at index j.

And using it (try it on the Go Playground):

var results []YourType

// Run your MongoDB query here

// Now sort it by Timestamp decreasing:
sort.Sort(ByTimestamp(results))

An alternative implementation for Less() would be to use Time.Before(), but compare element at index j to index i:

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

Try this variant on the Go Playground.