Golang use the sort interface to implement the sort example _golang

Source: Internet
Author: User
Tags key string

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.