Skip to main content
A function literal in Go represents an anonymous function—a function defined without an identifier. It evaluates to a function value at runtime, allowing functions to be treated as first-class citizens. Because it is an expression, a function literal can be assigned to a variable, passed as an argument, returned from another function, or invoked immediately.

Syntax

The syntax of a function literal is identical to a standard function declaration, but the function name is omitted.

Mechanics and Execution

Assignment to a Variable When assigned to a variable, the variable’s type becomes the function’s signature. The function can then be invoked using the variable identifier.
Immediate Invocation A function literal can be executed immediately at the point of its definition by appending an argument list to the end of the literal block.

Lexical Scoping and Closures

Function literals in Go are closures. They inherit the lexical scope in which they are defined. This means a function literal can reference and mutate variables declared in its surrounding function. The captured variables are not passed by value; the function literal retains a reference to the original variables, keeping them alive in memory for as long as the function value itself is accessible.

Type Identity

The underlying type of a function literal is strictly defined by its parameter types and return types. Two function literals share the same type if and only if they have the exact same sequence of parameter types and return types.
Tired of Poor Go Skills? Fix That With Deep Grasping!Learn More