dongmi5015 2015-03-16 10:49
浏览 339
已采纳

在golang中对降序结构进行排序

Please see this playground. What I want is quiet simple: I want to sort all "records" descending. I cannot figure out how. Reason is that my struct contains one or more records and I'm not sure how to handle that. (f.e. this works fine)

  • 写回答

2条回答 默认 最新

  • duangan9251 2015-03-16 12:03
    关注

    From your example, you are trying to sort the root element <records> instead of the sub-elements <record>.

    This example works better, with:

    • type ById []Record
    • sort.Sort(sort.Reverse(ById(records.Records)))

    Your Len(), Swap() and Less() methods remain unchanged, but use as a receiver a Record instance instead of Records.

    Output:

    {{ records} 
      [{{ record} 64321 http://golang.com} 
       {{ record} 3456 http://www.lommers.org/sampleurl} 
       {{ record} 4 http://www.this-is-my-url.com}]} 
    

    As I mention in "How to avoid re-implementing sort.Interface for similar golang structs", this changes with Go 1.8 and commit ad26bb5:

    You only define a Less() anonymous lambda

    a := ById(records.Records)
    sort.Slice(a, func(i, j int) bool {
        return a[i] > a[j]
    })
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?