Skip to content
This repository has been archived by the owner on Dec 30, 2018. It is now read-only.
This repository has been archived by the owner on Dec 30, 2018. It is now read-only.

Suggest Go 1.8 sort.Slice #27

Closed
bradleyfalzon opened this issue Nov 6, 2016 · 2 comments
Closed

Suggest Go 1.8 sort.Slice #27

bradleyfalzon opened this issue Nov 6, 2016 · 2 comments

Comments

@bradleyfalzon
Copy link

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)
}
@bradleyfalzon
Copy link
Author

bradleyfalzon commented Nov 28, 2016

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.

@dominikh
Copy link
Owner

@bradleyfalzon Please leave implementing the check to me, I already made some mental notes regarding its implementation.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

2 participants