Go - Function Closure



Go function closure is a function value that references variables from outside its body. The closures bind these variables and make them accessible even after closing the outer function.

Creating a Closure in Go

A closure is created when an inner function captures and retains access to the variables of its enclosing function. You can create a closure by following the below syntax:

// Creation
counter := func() func() int {
	count := 0
	return func() int {
		count++
		return count
	}
}
// Use
increment := counter()

Here, the counter function defines a local variable count, and the returned inner function, which will be known as closure, has access to count and modifies it on each call.

Example to Create a Simple Closure

In the following example we are creating a simple closure:

package main
import "fmt"

func main() {
    // First, define an outer function
    updateCounter := func() func() int {
        // define a local variable inside the function
        count := 100
        return func() int {
            count++
            return count
        }
    }

    // Now, creating a closure
    increment := updateCounter()

    // Using (calling) the closure
    fmt.Println(increment())
    fmt.Println(increment())
}

When the above code is compiled and executed, it produces the following result −

101
102

Passing Values into Closures

You can pass values into the closure while calling the function; you need to define the argument type during defining the nested function.

Example

The following example demonstrates passing the values to a closure:

package main
import "fmt"

func main() {
    // Define an outer function that accepts a value
    updateCounter := func(initial int) func() int {
        count := initial // Initialize count with the passed value
        return func() int {
            count++
            return count
        }
    }

    // Create a closure with an initial value
    inc_x := updateCounter(100)

    // Use the closure
    fmt.Println(inc_x())
    fmt.Println(inc_x())

    // Create another closure with an initial value
    inc_y := updateCounter(200)

    // Use the closure
    fmt.Println(inc_y())
    fmt.Println(inc_y())    
}

When the above code is compiled and executed, it produces the following result −

101
102
201
202
Advertisements