Functions as Return Variables
Explore how to return functions as variables in Go through closures. Understand creating incrementers, non-recursive Fibonacci functions, and factory functions that generate reusable behavior. This lesson helps you master advanced functional techniques useful for efficient Go programming and code organization.
We'll cover the following...
Returning a function using closures
Just like we return a variable or a value from a function, we can return a function too. The following function genInc returns a function:
// genInc creates an "increment n" function
func genInc(n int) func(x int) int {
return func(x int) int {
return x+n
}
}
It’s obvious from the header of genInc, that it’s returning a function that takes a parameter x of type int, and that function returns an int value. The function returned by genInc returns x+n.
The following program is an implementation of returning a function.
In the above program, we implement two functions Add2 and Adder, which return another lambda function. There is a header of Add2 at line 13. You can notice that it returns an anonymous function that takes b (of type int) as a parameter and returns an int value. That anonymous function is returning b+2. Similarly, there is a header Adder at line 18. You can notice that it takes a parameter a (of type int), and it also returns a closure that takes b (of type int) as a parameter and returns an int value. That closure is returning a+b.
Now, look at line 6 in main. We are calling Add2 and setting it equal to p2. Then, we call p2(3) at line 7, which calls the closure returned by Add2. So b of Add2 is equal to 3. On returning b+2, 5 will be printed. Similarly, look at line 9 in main. We are calling Adder(2) and setting it equal to TwoAdder. Then, we call TwoAdder(3) at line 10, which calls the closure returned by Adder. So b of Adder is equal to ...