Closures in Golang

Go has support for first-class functions, which means the functions can be used pretty much everywhere. This creates a new property for the function to become aware of its surroundings. This property is called the closure property.

What is Closure in Golang?

Closure occurs when an anonymous function in Go has access to its surroundings. Then it can hold a unique state of its own. The state then becomes isolated as we create new instances of the function.

Creating Closure in Go

The closure can be created when an anonymous function is declared. That function has access to its surrounding state and its state becomes unique.

package main

import (
	"fmt"
)

func main() {

	i := 42
	
	f := func() {
                // has access to i
		j := i/2
		fmt.Println(j)
	}
	
	f()      // 21
}

The code above has created a closure of the function f containing i. The anonymous function f can access the value i directly. This is the closure property.

Data isolation of a closure

Data isolation is a property that is available in the closure function. The state of the closures become unique when created. This makes each one of them having its own state. Here is an example.

package main

import (
	"fmt"
)

func f() func() int {
    i := 0
    return func() int {
        i+=10
        return i
    }
}

func main() {

	a := f()
	b := f()
	
	fmt.Println(a())        // 10
	fmt.Println(b())        // 10
	
	a()  // call a again
	
	// the difference suggests that they contains different state
	// a had an extra call that made it 30 while b is still 20
	
	fmt.Println(a())        // 30
	fmt.Println(b())        // 20
	
}

In the code above, a and b have isolated states. That becomes apparent when we invoke a function call that results in a mutation of the state. This is what makes closures very useful.

Uses of a Closure in Go Programming

The closure property is used extensively where data isolation is required. The state provided by the closures makes them immensely helpful in that regard. When we want to create a state encapsulated function we use closures to do that.