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)
}