Closures
This lesson covers the important concept of naming functions via closures.
We'll cover the following...
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: