BudiBadu Logo

Samplebadu

Code with Example
BudiBadu Logo
Samplebadu

Go by Example: Closures

Go 1.23

Understand Closures in Go, anonymous functions that can capture and maintain state from their surrounding scope. This example demonstrates how to create closures, how they isolate data, and their utility in functional programming patterns.

Code

package main

import "fmt"

// intSeq returns a function that yields the next int
func intSeq() func() int {
    i := 0
    return func() int {
        i++
        return i
    }
}

func main() {
    // Create a new generator
    nextInt := intSeq()

    // Call it a few times
    fmt.Println(nextInt())
    fmt.Println(nextInt())
    fmt.Println(nextInt())

    // Create another generator, separate state
    newInts := intSeq()
    fmt.Println(newInts())
}

Explanation

Go supports anonymous functions, which can form closures. A closure is a function value that references variables from outside its body. The function may access and assign to the referenced variables; in this sense the function is "bound" to the variables.

Closures are powerful because they "capture" variables from their surrounding scope, maintaining the state of those variables even after the outer function has returned. This allows for data isolation and stateful functions without using global variables or structs.

Key concepts of closures:

  • Variable Capturing: Inner functions retain access to variables defined in their outer scope.
  • State Persistence: Captured variables survive as long as the closure exists.
  • Data Isolation: Each closure instance has its own independent state.
  • Use Cases: Generators, middleware, event handlers, and functional options.

Code Breakdown

6-11
The intSeq function returns an anonymous function (func() int). The variable "i" is defined outside the anonymous function but is used inside it. This captures "i" in the closure.
16
We assign the result of intSeq to nextInt. This variable now holds the closure function, which has its own internal "i" variable initialized to 0.
24-25
Creating a new closure "newInts". This creates a completely separate instance of the variable "i", proving that state is unique to each closure instance.