Closure In Go

In Go, a closure is a function value that references variables from its surrounding lexical scope. The closure “encloses” or captures the variables it references, allowing it to access and manipulate those variables even when it is invoked in a different scope. Here’s an example to illustrate closures in Go:

package main

import "fmt"

func outer() func() {
    count := 0

    inner := func() {
        count++
        fmt.Println("Count:", count)
    }

    return inner
}

func main() {
    increment := outer()
    increment() // Count: 1
    increment() // Count: 2
}

In this example, the outer function returns an inner function, which is assigned to the increment variable in the main function. The inner function has access to the count variable defined in the outer function’s lexical scope.

When increment is called, it increments the count variable and prints its value. The count variable is preserved across multiple invocations of increment because it is captured by the closure.

The output of this program will be:

Count: 1
Count: 2

Closures are commonly used in Go for several purposes, including:

  • Creating and using function factories: Closures can be used to create functions on-the-fly with pre-configured behavior or state.
  • Maintaining state across multiple function calls: Closures can capture and update variables, allowing them to maintain state between invocations.
  • Implementing callbacks and event handlers: Closures can be passed as arguments to other functions to provide custom behavior or context.

Here’s an example that demonstrates closures being used as function factories:

package main

import "fmt"

func adder(base int) func(int) int {
    return func(num int) int {
        return base + num
    }
}

func main() {
    add := adder(5)
    result := add(3) // 5 + 3
    fmt.Println("Result:", result) // Result: 8
}

In this example, the adder function returns a closure that adds a given num to a base value. When adder(5) is called, it returns a closure that adds 5 to the provided num. The returned closure is assigned to the add variable, which can then be used as a function to perform the addition.

Closures in Go provide a powerful mechanism for encapsulating behavior and managing state within functions. They enable more flexible and expressive code by allowing functions to access and manipulate variables from their lexical context.