loading...
Cover image for Playing with Go: Functions as a parameter

Playing with Go: Functions as a parameter

flrnd profile image Florian Rand Updated on ใƒป2 min read

Fantastic cover image thanks to golang.org

There are a few things very terrifying for beginners when we are learning to code. One of them is passing functions as a parameter to other functions.

Functions are first class values in Go: Like other values, functions values have types, and they may be assigned to variables or passed to or returned from functions. A function value may be called like any other funcion. - The Go Programming Language, Alan A. A. Donovan, Brian W. Kernighan

Have you ever wonder why do we pass functions in the first place? If you are an experienced engineer you probably already know the answer. There is a lot of good reads and tutorials about how to pass functions as parameter to other functions, but if you add why to the formula, the results are a bit scarce.

The perfect example is a Map() function

func Map(n []int, f func(x int) int) []int {
   result := make([]int, len(n))
    for i, v := range n {
        result[i] = f(v)
    }
    return result
}

With the same function we can have different behaviours just changing the callback function! Let's see another example:

In this example, as we can see, double and square are both variables with function values of type func (int) int, remember our definition at the beginning? The important thing here is that we didn't modified our Map function. Instead, we added the flexibility to parametrize it's behaviour thanks to the function callbacks! How awesome is that?

And this is one example why languages that let you treat functions as a first class values are so powerful!

Please, keep in mind that I'm learning! if you find something that can be optimized or better explained let me know! I'd love to hear about it!

Happy asking why the #%&?!

Posted on May 15 '19 by:

flrnd profile

Florian Rand

@flrnd

Designer and Software developer. Very bad writer. I love cats and skateboarding. more ? ๐Ÿป : ๐Ÿ––;

Discussion

markdown guide