Functions as Return Variables

This lesson discusses how to use a function as a return variable or value.

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.

Get hands-on with 1000+ tech skills courses.

Learn to code, grow your skills, and succeed in your tech interview