dongsi7759 2016-11-28 10:52 采纳率: 100%
浏览 418
已采纳

结构/结果的倒序排列

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?

  • 写回答

1条回答 默认 最新

  • dp9599 2016-11-28 11:15
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器