Created
June 19, 2012 17:17
-
-
Save jordanorelli/2955370 to your computer and use it in GitHub Desktop.
sorting heterogenous slices in go
This file contains hidden or 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
package main | |
import ( | |
"fmt" | |
"sort" | |
) | |
type CommonCollection []Convertible | |
func (c CommonCollection) Len() int { return len(c) } | |
func (c CommonCollection) Less(i, j int) bool { return c[i].Common().Name < c[j].Common().Name } | |
func (c CommonCollection) Swap(i, j int) { c[i], c[j] = c[j], c[i] } | |
type Convertible interface { | |
Common() *Common | |
} | |
type Common struct { | |
Name string | |
} | |
type TypeOne struct { | |
Name string | |
} | |
func (t TypeOne) Common() *Common { | |
return &Common{Name: t.Name} | |
} | |
type TypeTwo struct { | |
NotAName string | |
} | |
func (t TypeTwo) Common() *Common { | |
return &Common{Name: t.NotAName} | |
} | |
func main() { | |
onesies := []TypeOne{ | |
TypeOne{"stanley"}, | |
TypeOne{"norbert"}, | |
TypeOne{"david"}, | |
} | |
twosies := []TypeTwo{ | |
TypeTwo{"agatha"}, | |
TypeTwo{"gertrude"}, | |
TypeTwo{"martha"}, | |
} | |
all := CommonCollection{} | |
for _, v := range onesies { | |
all = append(all, v) | |
} | |
for _, v := range twosies { | |
all = append(all, v) | |
} | |
sort.Sort(all) | |
fmt.Println(all) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment