Skip to content

Instantly share code, notes, and snippets.

@vancluever
Created December 10, 2015 21:48
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vancluever/67b427edf24717d3466f to your computer and use it in GitHub Desktop.
Save vancluever/67b427edf24717d3466f to your computer and use it in GitHub Desktop.
Go: Sort an array of interfaces so that strings are on top
// This is a very basic demonstration of how to implement sort.Interface
// to do some custom sorting. Here, a slice of interfaces
// (ints and strings) are sorted so that the strings are on top.
// There is no other sorting of the elements, but the example
// provides a layout that can be used to implement more complex sorting.
package main
import "fmt"
import "sort"
type MultiArray []interface{}
func (a MultiArray) Len() int { fmt.Printf("%s\n", a) ; return len(a) }
func (a MultiArray) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a MultiArray) Less(i, j int) bool {
switch a[i].(type) {
case string:
fmt.Println("found string")
return true
}
return false
}
func main() {
foo := []interface{} {
"foo",
42,
"bar",
84,
}
fmt.Printf("%d\n", len(foo))
sort.Sort(MultiArray(foo))
fmt.Printf("%s\n", foo)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment