Skip to content

Instantly share code, notes, and snippets.

@dyoo
Created July 25, 2013 19:59
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/6083199 to your computer and use it in GitHub Desktop.
Save dyoo/6083199 to your computer and use it in GitHub Desktop.
A few notes on how to use Go's sort, and observation on how the language features interact.
// A little bit of play with Go's sorting routines, coupled with
// type system stuff.
// Let's say that we'd like to sort a list of numbers in reverse
// order. (and pretend that we know about sort.Sort(), but neglected
// to read about sort.Reverse(). Let's start this off:
package main
import (
"fmt"
"sort"
)
// We can define a wrapper around int slices. We are implementing
// sort.Interface.
// (Aside: what might be a little novel here for folks from a
// different language is this: the comparison customization is being
// done on the container, rather than on the items.)
type MyList []int
func (l MyList) Len() int { return len(l) }
func (l MyList) Less(i, j int) bool { return l[i] >= l[j] }
func (l MyList) Swap(i, j int) { l[i], l[j] = l[j], l[i] }
// Let's try it out.
func main() {
vals := []int{3, 1, 4, 1, 5, 9, 2, 6}
lst := MyList(vals)
// We've "wrapped" lst here.
// What's important to note here is that lst has the same same
// representation as vals, but with a different static type. To
// emphasize: vals and lst are both really the identical
// representation of these numbers! Let's look at their pointer
// addresses to confirm this.
fmt.Printf("%p\n", lst)
fmt.Printf("%p\n", vals)
// It's the same address! So when we say we're "wrapping" it, we
// must make the following qualification: we're doing the wrapping
// at the type-system level, not the runtime-system level.
// Now to sort...
sort.Sort(lst)
// .. and we can see that we've sorted the shared value by
// printing it out.
fmt.Printf("%#v\n", lst)
fmt.Printf("%#v\n", vals)
// Note that printf is printing the values differently!
// It can distinguish between the two, because Printf takes in
// interface arguments. The use of the interfaces by Printf
// provokes Go to reify the static type information into the
// interface value, where it can later inspect that information
// via reflection.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment