Go Closure

In Go, a closure is a function value that references variables from outside its body. A closure can be thought of as a function that "encloses" its surrounding state, allowing it to maintain and modify state across multiple function calls.

Here's an example of a closure in Go:

refer ‮igi:ot‬ftidea.com
package main

import "fmt"

func makeCounter() func() int {
    count := 0
    return func() int {
        count++
        return count
    }
}

func main() {
    counter := makeCounter()

    fmt.Println(counter()) // prints "1"
    fmt.Println(counter()) // prints "2"
    fmt.Println(counter()) // prints "3"
}

In this example, the makeCounter function returns a closure that references the count variable from its surrounding scope. The closure increments the count variable each time it is called and returns its current value. The counter variable in the main function is assigned the closure returned by makeCounter, allowing it to maintain and modify the count variable across multiple function calls.