Suggest Go 1.8 sort.Slice
Closed this issue · 2 comments
Pre 1.8 to sort a slice of person by age:
package main
import (
"fmt"
"sort"
)
type Person struct {
Name string
Age int
}
type ByAge []Person
func (a ByAge) Len() int { return len(a) }
func (a ByAge) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
func (a ByAge) Less(i, j int) bool { return a[i].Age < a[j].Age }
func main() {
people := []Person{
{"Bob", 31},
{"John", 42},
{"Michael", 17},
{"Jenny", 26},
}
fmt.Println(people)
sort.Sort(ByAge(people))
fmt.Println(people)
}
Post 1.8 using https://tip.golang.org/pkg/sort/#Slice
package main
import (
"fmt"
"sort"
)
type Person struct {
Name string
Age int
}
func main() {
people := []Person{
{"Bob", 31},
{"John", 42},
{"Michael", 17},
{"Jenny", 26},
}
fmt.Println(people)
sort.Slice(people, func(i, j int) bool { return people[i].Age < people[j].Age })
fmt.Println(people)
}
Go 1.8 adds the following slice helpers to the sort package
Slice(slice interface{}, less func(i, j int) bool)
SliceIsSorted(slice interface{}, less func(i, j int) bool) bool
SliceStable(slice interface{}, less func(i, j int) bool)
It appears we could just check for calls to sort.Slice{,Stable,IsSorted}
with a slice (taking into account a possible cast to something that implements sort.Interface). If it's a slice, we can suggest a simplification to sort.Slice{,Stable,IsSorted}
.
I can't imagine any conceivable reasons someone may want to ignore the suggestion, as I can't imagine anyone implementing the Len
or Swap
methods any differently.
Would it be safe to implement this check, and if a maintainer wants to support pre Go 1.8, they can use the ignore flags?
If no-one has any immediate concerns/suggestions/alternatives, I may attempt to implement this check myself soon.
@bradleyfalzon Please leave implementing the check to me, I already made some mental notes regarding its implementation.