Description
Proposal Details
This proposal is for expanding the sort package in the stdlib to use generics. The Sort and Slices packages have been updated to use generics to cover all other functions in the sort package, but calling Sort() on an arbitrary data structure still requires that the provided Interface
implements Less(i, j int) bool
and Swap(i, j int)
instead of allowing for generics. This would be helpful for cases where the primary keys/values of an ordered data structure are not integers.
Example:
package main
import (
"fmt"
"slices"
"sort"
)
//**want to use this interface**
type CustomDataInterface interface {
Len() int
Less(a, b string) bool
Swap(a, b string)
}
type CustomData struct {
Dat []string
}
func (cd *CustomData) Len() int {
return len(cd.Dat)
}
func (cd *CustomData) Less(a, b string) bool {
return a < b
}
func (cd *CustomData) Swap(a, b string) {
idxA := slices.IndexFunc(cd.Dat, func(x string) bool { return x == a })
idxB := slices.IndexFunc(cd.Dat, func(x string) bool { return x == b })
cd.Dat[idxA] = b
cd.Dat[idxB] = a
return
}
func main() {
letters := []string{"b", "a", "c", "d"}
CD := &CustomData{Dat: letters}
fmt.Printf("%v", CD.Dat)
fmt.Println()
//slices.Sort(CD.Dat) //works for slices
sort.Sort(CD)
fmt.Printf("%v", CD.Dat)
}
./prog.go:46:12: cannot use CD (variable of type *CustomData) as sort.Interface value in argument to sort.Sort: *CustomData does not implement sort.Interface (wrong type for method Less) have Less(string, string) bool want Less(int, int) bool
It looks like this wouldn't be too difficult to implement since the sort package already has some generated code for generics. I also didn't find other issues mentioning this proposal but may be missing something obvious.