Closures and Currying

Go’s support for functions as values enables advanced patterns like closures and currying.

Closures

A closure is a function that “closes over” or references variables from outside its own body. The function keeps access to those variables even after the outer function has finished executing.

func adder() func(int) int {
    sum := 0
    return func(x int) int {
        sum += x
        return sum
    }
}

func main() {
    myAdder := adder()
    fmt.Println(myAdder(10)) // 10
    fmt.Println(myAdder(5))  // 15 (sum was preserved)
}

Currying

Currying involves transforming a function that takes multiple arguments into a sequence of functions that each take a single argument. This is useful for “partial application” of logic.

func selfMath(mathFunc func(int, int) int) func(int) int {
    return func(x int) int {
        return mathFunc(x, x)
    }
}

func main() {
    squareFunc := selfMath(multiply)
    fmt.Println(squareFunc(5)) // 25
}