Usually Named functions in Go can be declared only at the package level. But to ease developer’s life , Go allows function literals to denote a function value within any expression.

So What’s a function literal? It’s same as a function with body but misses a name. So these anonymous functions are same as the functions in Javascript territory.

These functions have access to the entire lexical environment. So the innermost function can get access to the variables from the enclosing functions.

So from the Screen Grab, appendArray() is a function which returns some anonymous function func() []int . A call to the appendArray() creates a local variable x and y and return the anonymous function that, each time it is called, increments x and appends y. A second call to appendArray() creates second local variable x and y and it increments that variable and returns the function.

That satisfies the Go Prophecy , Functions are Reference Types and Function Values are not comparable.

So the Anonymous functions can remember the state of their local variable and can access and update the local variables of the enclosing function.

This special property of memorizing the state of the variables helps us to solve many problems in Computer science very easily , for example , the topological sorting to compute the career path of a Full stack developer.

So next time you define an Api , see yourself the power of Go Closures.