Created
December 10, 2015 21:48
-
-
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 file contains 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
// 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