【问题标题】:Sort descending struct in golang在golang中对结构进行降序排序
【发布时间】:2015-03-16 10:49:20
【问题描述】:

请参阅this playground。我想要的很简单:我想对所有“记录”进行降序排序。我不知道怎么做。原因是我的结构包含一个或多个记录,我不确定如何处理。 (例如this 工作正常)

【问题讨论】:

  • 看起来您只是盲目地从其他地方剪切-n-粘贴的代码,而丝毫不知道发生了什么。无论您在做什么,这种方法都不适合您。

标签: xml sorting struct go


【解决方案1】:

your example 开始,您尝试对根元素<records> 而非子元素<record> 进行排序。

This example 效果更好,与:

  • 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}]} 

正如我在“How to avoid re-implementing sort.Interface for similar golang structs”中提到的,这会随着 Go 1.8 和 commit ad26bb5 而改变:

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

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

【讨论】:

  • 如果你真的想在 ReadingListRecords 上进行排序(或者只是像 VonC 建议的那样在 []Records 上进行排序,但绝对不是[]ReadingListRecords 上,因为你有它) 你只需要改变你的sort.Interface 方法,你知道,实际上可以使用ReadingListRecords。例如。 len(a.Records); a.Record[i]、a.Record[j] 等
【解决方案2】:

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

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

sort.Sort(data)

然后你可以通过将其更改为:

sort.Sort(sort.Reverse(data))

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

【讨论】:

  • 感谢您的回复,但我一开始无法排序 :)。你能看看我的操场(play.golang.org/p/O6k9Km1l-C)吗?我不知道将什么传递给排序函数。
猜你喜欢
  • 2013-11-25
  • 2020-09-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-25
  • 1970-01-01
相关资源
最近更新 更多