Sort descending struct in golang

huangapple go评论85阅读模式
英文:

Sort descending struct in golang

问题

请查看这个示例。我想要的很简单:我想要按降序对所有的"records"进行排序。我无法弄清楚如何做到这一点。原因是我的结构体包含一个或多个记录,我不确定如何处理它们。(例如,这个示例可以正常工作)

英文:

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)

答案1

得分: 7

你的示例中,你试图对根元素<records>进行排序,而不是子元素<record>

这个示例效果更好,使用了以下代码:

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

你的Len()Swap()Less()方法保持不变,但是将Record实例作为接收器使用,而不是Records

输出结果:

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

正如我在“如何避免为类似的golang结构重新实现sort.Interface”中提到的,这在Go 1.8和提交ad26bb5中发生了变化:

你只需要定义一个Less()匿名lambda函数:

a := ById(records.Records)
sort.Slice(a, func(i, j int) bool {
    return a[i] > a[j]
})
英文:

From your example, you are trying to sort the root element &lt;records&gt; instead of the sub-elements &lt;record&gt;.

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] &gt; a[j]
})

答案2

得分: 4

如果你有一个按升序排序的sort.Interface实现,你可以使用sort.Reverse函数生成一个按降序排序的版本。

所以如果data实现了sort.Interface,并且你有一个像这样的调用:

sort.Sort(data)

那么你可以通过将其改为以下方式来切换到降序排序:

sort.Sort(sort.Reverse(data))

在内部,sort.Reverse返回的排序器只是直接通过sort.Interface方法调用进行代理,除了Less方法,在这个方法中它交换了两个参数的位置。

英文:

If you have a sort.Interface implementation that sorts in ascending order, you can use the sort.Reverse function to produce a version that will sort in reverse.

So if data implements sort.Interface and you have a call like:

sort.Sort(data)

Then you can switch to descending order by changing it to:

sort.Sort(sort.Reverse(data))

Internally, the sorter returned by sort.Reverse just proxies the sort.Interface method calls straight through with the exception of Less where it switches the two arguments.

huangapple
  • 本文由 发表于 2015年3月16日 18:49:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/29074972.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定