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

Sort descending struct in golang

请参阅 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 工作正常)

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

因此,如果 data 实现了 sort.Interface 并且您有这样的调用:

sort.Sort(data)

然后你可以切换到降序,将其更改为:

sort.Sort(sort.Reverse(data))

在内部,sort.Reverse 返回的排序器直接代理 sort.Interface 方法调用,但 Less 除外,它会切换两个参数。

your example 开始,您正在尝试对根元素 <records> 而不是子元素 <record>.

进行排序

This example 效果更好,与:

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

您的 Len()Swap()Less() 方法保持不变,但使用 Record 实例而不是 Records.[=25 作为接收者=]

输出:

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

正如我在“", this changes with Go 1.8 and commit ad26bb5:

你只定义一个Less()匿名lambda

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