Skip to content

Instantly share code, notes, and snippets.

@nathanleclaire
Created May 26, 2017 19:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nathanleclaire/b4fff4601f2ecb25a1549aa3da2592c0 to your computer and use it in GitHub Desktop.
Save nathanleclaire/b4fff4601f2ecb25a1549aa3da2592c0 to your computer and use it in GitHub Desktop.

Sorting in Golang, the old (pre-1.8) way:

type ByLength []string

func (s ByLength) Len() int {
    return len(s)
}

func (s ByLength) Swap(i, j int) {
    s[i], s[j] = s[j], s[i]
}

func (s ByLength) Less(i, j int) bool {
    return len(s[i]) < len(s[j])
}

func main() {
    fruits := []string{"peach", "banana", "kiwi"}
    sort.Sort(ByLength(fruits))
    fmt.Println(fruits)
}

Sorting in Golang, the new way:

func main() {
    fruits := []string{"peach", "banana", "kiwi"}
    sort.Slice(fruits, func(i, j int) bool {
        return len(fruits[i]) < len(fruits[j])
    })
    fmt.Println(fruits)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment