Closures

This lesson covers the important concept of naming functions via closures.

Using function literals

Sometimes, we do not want to give a function a name. Instead, we can make an anonymous function (also known as a lambda function, a function literal, or a closure), for example:

func(x, y int) int { return x + y }

Such a function cannot stand on its own (the compiler gives the error: non-declaration statement outside function body), but it can be assigned to a variable which is a reference to that function:

fplus := func(x, y int) int { return x + y }

Then it can be invoked as if fplus was the name of the function:

fplus(3,4)

or it can be invoked directly:

func(x, y int) int { return x + y } (3, 4)

Here is a call to a lambda function, which calculates the sum of integer floats till 1 million. The gofmt reformats the lambda function in this way:

func() {
    sum = 0.0
    for i := 1; i<= 1e6; i++ {
        sum += i
    }
}()

The first ( ) is the parameter-list, and it follows immediately after the keyword func because there is no function name. The { } comprise the function body, and the last pair of ( ) represent the call to the function.

Here is an example of assigning a function literal to a variable:

Get hands-on with 1400+ tech skills courses.