There is one problem bothering me in Golang. Say I have 2 structs:
type Dog struct {
Name string
Breed string
Age int
}
type Cat struct {
Name stri
Note: as illustrated in commit ad26bb5, in Go 1.8 (Q1 2017), you won't have to implement Len()
and Swap()
and Less()
since issue 16721 was resolved. Only Less()
is needed, the rest is done by reflection.
The problem was:
- Vast majority of sort.Interface uses a slice
- Have to define a new top level type
Len
andSwap
methods are always the same- Want to make common case simpler with least hit to performance
See the new sort.go:
// Slice sorts the provided slice given the provided less function.
//
// The sort is not guaranteed to be stable. For a stable sort, use
// SliceStable.
//
// The function panics if the provided interface is not a slice.
func Slice(slice interface{}, less func(i, j int) bool) {
rv := reflect.ValueOf(slice)
swap := reflect.Swapper(slice)
length := rv.Len()
quickSort_func(lessSwap{less, swap}, 0, length, maxDepth(length))
}
So as long as you have a Less()
function comparing two instances respecting an interface, you can sort any number of struct respecting said common interface.