Created
December 17, 2017 15:32
-
-
Save bilxio/6caf733b4ee39eaad64296fcb05d3b04 to your computer and use it in GitHub Desktop.
sorting in Golang
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package main | |
| import ( | |
| "sort" | |
| "fmt" | |
| ) | |
| type Msg struct { | |
| Name string | |
| Size int | |
| } | |
| type msgSlice []*Msg | |
| func (s msgSlice) Len() int { return len(s) } | |
| func (s msgSlice) Swap(i, j int) { s[i], s[j] = s[j], s[i] } | |
| func (s msgSlice) Less(i, j int) bool { return (*s[i]).Size < (*s[j]).Size } | |
| func main() { | |
| mm := msgSlice { | |
| &Msg{"Haha", 1}, | |
| &Msg{"Lala", 4}, | |
| &Msg{"Aaaa", 2}, | |
| } | |
| // sort | |
| // sort.Stable(mm) | |
| // or sort reverse | |
| sort.Stable(sort.Reverse(mm)) | |
| for i := range mm { | |
| fmt.Println(*mm[i]) | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment