Introduction
This challenge aims to test your ability to sort a collection by something other than its natural order. In this case, we will sort strings by their length instead of alphabetically.
This tutorial is from open-source community. Access the source code
This challenge aims to test your ability to sort a collection by something other than its natural order. In this case, we will sort strings by their length instead of alphabetically.
The problem to be solved in this challenge is to implement a custom sort function in Go that sorts a slice of strings by their length.
byLength
type should be created as an alias for the []string
type.sort.Interface
should be implemented on the byLength
type.Len
and Swap
functions should be implemented on the byLength
type.Less
function should be implemented on the byLength
type to hold the actual custom sorting logic.main
function should convert the original fruits
slice to byLength
, and then use sort.Sort
on that typed slice.## 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 `Interface` methods on that
## type, and then calling sort.Sort on a collection of that
## custom type, we can sort Go slices by arbitrary
## functions.
In this challenge, we learned how to sort a collection by something other than its natural order. We implemented a custom sort function in Go that sorts a slice of strings by their length.