Go by Example: Sorting by Functions
Go by Example : Sorting by Functions
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 in Go. | |
| |
| |
| |
We implement a comparison function for string
lengths.
|
|
Now we can call
|
|
We can use the same technique to sort a slice of values that aren’t built-in types. |
|
| |
Sort
Note: if the
|
|
|
Next example: Panic .