Sometimes we’ll want to sort a collection by something other than its natural order. For example, suppose we wanted to sort strings by their length instead of alphabetically. Here’s an example of custom sorts sorts in Go. |
|
package main
|
|
import "sort"
import "fmt"
|
|
In order to sort by a custom function in Go, we need a
corresponding type. Here we’ve created a |
type ByLength []string
|
We implement |
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])
}
|
With all of this in place, we can now implement our
custom sort by casting the original |
func main() {
fruits := []string{"peach", "banana", "kiwi"}
sort.Sort(ByLength(fruits))
fmt.Println(fruits)
}
|
Running our program shows a list sorted by string length, as desired. |
$ go run sorting-by-functions.go
[kiwi peach banana]
|
By following this same pattern of creating a custom
type, implementing the three |
Next example: Panic.