Search⌘ K

Closures

Explore how to use closures and anonymous functions in Go programming. Understand function literals, their assignment to variables, and how closures capture and share state within the surrounding function. Learn practical uses such as wrapper functions, deferred execution with the defer keyword, and launching goroutines.

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
...