If Go had generics
If Go had generics, we could have written a function signature like the following to replace strings with runes, and we would not have to rewrite the inner logic:
func Map(f func(v <string>) <bool>, vs [] <string>) []<bool>
However, Go does not have generics, so we can use empty interfaces and reflection to achieve the same result.
Map function
Let's create a Map function to transform the contents of a Collection.
First, let's define Object to be the empty interface type and create a Collection type to be a slice of objects:
package main
import "fmt"
type Object interface{}
type Collection []Object
func NewCollection(size int) Collection {
return make(Collection, size)
}The NewCollection function creates a new instance of the collection with the given size:
type Callback func(current, currentKey, src Object) Object
The Callback type is a first-class function type that returns the calculated result:
func Map(c Collection, cb Callback) Collection {
...