Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

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.
func(parameter_list) (result_list) {
    // function body
}

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.
// The variable 'multiply' holds a function value of type: func(int, int) int
multiply := func(x int, y int) int {
    return x * y
}

result := multiply(4, 5) // Evaluates to 20
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.
// The literal is defined and immediately invoked with arguments (10, 2)
quotient := func(a float64, b float64) float64 {
    return a / b
}(10, 2) // Evaluates to 5.0

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.
func createCounter() func() int {
    count := 0 // Local variable in the outer function
    
    // The function literal captures the 'count' variable
    return func() int {
        count++ // Mutates the captured variable directly
        return count
    }
}

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.
var operation func(int, int) int

// Valid assignment: signature matches func(int, int) int
operation = func(a int, b int) int { return a + b }

// Invalid assignment: signature func(int) int does not match
// operation = func(a int) int { return a * 2 } // Compiler error
Master Go with Deep Grasping Methodology!Learn More