Skip to content

Instantly share code, notes, and snippets.

@bilxio
Created December 17, 2017 15:32
Show Gist options
  • Select an option

  • Save bilxio/6caf733b4ee39eaad64296fcb05d3b04 to your computer and use it in GitHub Desktop.

Select an option

Save bilxio/6caf733b4ee39eaad64296fcb05d3b04 to your computer and use it in GitHub Desktop.
sorting in Golang
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