在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)

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

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.