Because Google Go (Golang) is not a functional language, it does not include a standard library full of functional utilities like map/filter/all/any. With a little of coding, we accomplish this in a few lines.
We write a Collect
method, similar to Ruby’s map
method. This function produces a new array of values by mapping each value in list through a transformation function. The transformation function is passed as an arguments into the Collect
. Here’s a simple example that will handle an array or slice of strings:
Because Go is a strongly typed language, we need to write a different function that accepts parameters of different types. Here’s an example that will map our custom car
struct to a string.
However, we run into trouble if we try to overload the collect for the int
type
The above code will result in:
src/collect3.go:23: Collect redeclared in this block previous declaration at src/collect3.go:11
src/collect3.go:42: cannot use getMake (type func(car) string) as type func(car) int in argument to Collect
src/collect3.go:47: cannot use getModel (type func(car) string) as type func(car) int in argument to Collect
This is because Golang does not allow overloading of methods. This was a language design decision made to enhance the performance of Go.