Using functions as objects
In the preceding section, we saw how to create type aliases to make our code more readable when dealing with functions. In this section, let’s take a brief look at how functions can be used in the same way as objects. This is the essence of what it means to be first-class.
Passing functions to functions
We can pass functions to functions as in the preceding filter function:
type predicate func(int) bool func largerThanTwo(i int) bool { return i > 2 } func filter(is []int, p predicate) []int { out := []int{} for _, i := range is { if p(i) { out = append(out, i) } } return out } func main() { ints := []int{1, 2, 3} filter(ints, largerThanTwo) }
In this example, we have created the largerThanTwo
function, which adheres to the predicate
type alias. Note that we don’t have to specify anywhere that this function adheres to our predicate
type; the compiler will figure this out during compile time, just like it does for...