Learning Functional Programming in Go
上QQ阅读APP看书,第一时间看更新

Reflection

Our implementation of predicates is performant but restrictive. Take the Any() function signature, for example:

func Any(vs []string, predicate func(string) bool) bool

The Any function only works for slices of string. What if we wanted to iterate over a tree or map structure? We'd have to write separate functions for each. This is a valid argument for requesting Go to support generics. If Go supported generics, our implementations would likely require much less code.

An alternative implementation could be to use empty interfaces. This would solve the problem of having to implement separate functions for each type of data we want to handle, given that an empty interface can take on a value of any type. To use a value of the interface{} type, you must use reflection or type assertion or a type switch to determine the type of value, and there will be a performance hit for any of those methods.

Another alternative implementation could be to use Goroutines and channels. Itertools uses empty interfaces, Goroutines, and channels. 

The github.com/ahl5esoft/golang-underscore is a package that uses a lot of reflection and empty interfaces to provide an underscore-like implementation of high-order functions.