Tianchi YU's Blog

Learning GoLang - Day 2 : Higher Order Functions & Closures

Today I was impressed by the features of Golang functions. We consider Golang as a multi-paradigms programming language, the existence of Closures and Anonymous Functions explains its functional features.

Golang is not a functional language but has a lot of features that enable us to apply functional principles in development, making our code more elegant, concise, maintainable, and easier to understand and test. (-- From Internet)

As you (probably) know, one of the key features of functional language is that it treats functions as first-class citizens, as variables. You can take a function as the argument of other functions or take it as output/return of other functions, by which to create higher order functions. You can do the same things in Golang. The functions are variables here.

func square() func(num int) int{
    return func(num int) int{
        return num*num
    }
}

func getValues(f func(max int) (int, int)) {
    x, y = f(35)
    fmt.Println(x,y)
}

func fibonacci() func() int {
    a,b := 0,1
    return func() int {
        defer a, b = b, a+b
        return a
    }
}

I believe you have noticed that, there is something "bizarre" with the above snippets of code. Firstly, anonymous functions play an important role up there. An anonymous function can also be called a function literal, or lambda function. The Literal concept is very common in Golang. So far so good, until you saw the fibonacci function. How could it work as a Fibonacci Calculator? If you do similar things in other languages like C or C++, the memory of a and b would be destroyed out of the scope of fibonacci function, and you can only get repeated 0 even if you call the function repeatedly.

The truth is, if you consider the functions as variables, naming them Closures (the instance of functions), you can reference their inclusive variables outside of its scope. Mindblowing!

Are they useful? Certainly!
Here are some useful ways to use closures in Go, I don't like to offer some redundant content to you, so please check them by yourself. In a nutshell, using closures helps us to better isolate data(make it invisible but maybe "accessible" indirectly), wrap functions, create middleware, etc.

That is the end of today's GoLang study, see you tomorrow!

#golang