This example describes how Golang uses the sort interface to implement sorting. Share to everyone for your reference, specific as follows:
See the group today to discuss sorted sort again. The realization of interface, there are children's shoes have been uncertain, I started a bit, oh yes, the code is here.
Actually very simple sort. Interface three ways to implement these three methods for your own struct, and then pass your own structure to sort. The sort method is sorted to complete.
Of course the sort package also has several common methods of sort. Float64slice sort. Intslise sort. Stringslise, hehe
Copy Code code as follows:
Package Main
Import (
"FMT"
"Sort"
)
Type Mapsorter []item
Type Item struct {
Key string
Val Int64
}
Func Newmapsorter (M Map[string]int64) Mapsorter {
MS: = Make (Mapsorter, 0, Len (m))
For k, V: = range m {
ms = Append (MS, item{k, v})
}
Return MS
}
Func (MS Mapsorter) Len () int {
Return Len (MS)
}
Func (MS Mapsorter) Less (i, J int) bool {
Return ms[i]. Val < Ms[j]. Val//sorted by value
Return ms[i]. Key < Ms[j]. Key//Key sorting
}
Func (MS Mapsorter) Swap (i, J int) {
Ms[i], ms[j] = Ms[j], ms[i]
}
Func Main () {
M: = Map[string]int64 {
"E": 10,
"A": 2,
"D": 15,
"C": 8,
"F": 1,
"B": 12,
}
MS: = Newmapsorter (M)
Sort. Sort (MS)
For _, Item: = Range MS {
Fmt. Printf ("%s:%d\n", item. Key, item. Val)
}
}
I hope this article will help you with your go language program.