Skip to content

Instantly share code, notes, and snippets.

@dyoo
Created August 11, 2013 20:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dyoo/6206710 to your computer and use it in GitHub Desktop.
Save dyoo/6206710 to your computer and use it in GitHub Desktop.
More play with Go; sorting with a comparison function. It's interesting to note that we have to do type conversions that we wouldn't have to do if we were to go along the grain of the sort.Sort() function.
package main
import (
"fmt"
"sort"
)
type ComparableSlice struct {
elts []interface{}
cmp func(interface{}, interface{}) bool
}
func (c ComparableSlice) Len() int {
return len(c.elts)
}
func (c ComparableSlice) Less(i, j int) bool {
return c.cmp(c.elts[i], c.elts[j])
}
func (c ComparableSlice) Swap(i, j int) {
c.elts[i], c.elts[j] = c.elts[j], c.elts[i]
}
func SortComparables(elts []interface{},
cmp func(interface{}, interface{}) bool) {
sort.Sort(ComparableSlice{elts, cmp})
}
//////////////////////////////////////////////////////////////////////
// Let's try using this:
func RuneLessThan(o1 interface{}, o2 interface{}) bool {
return o1.(rune) < o2.(rune)
}
func main() {
msg := "Hello world!"
comparables := make([]interface{}, len(msg))
for i, v := range msg {
comparables[i] = v
}
SortComparables(comparables, RuneLessThan)
sortedRunes := make([]rune, len(msg))
for i, v := range comparables {
sortedRunes[i] = v.(rune)
}
fmt.Printf("result: %#v\n", string(sortedRunes))
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment