How to use closures in Golang?

Go ProgrammingServer Side ProgrammingProgramming

In order to understand what closures are, we must know what anonymous functions are and how we can use them.

Anonymous functions

In Go, anonymous functions are those functions that don't have any name. Simply put, anonymous functions don't use any variables as a name when they are declared.

We know that we declare a function with a similar syntax as shown below.

func Sample(){
   // some code
}

While we do have a name for the above function (Sample), in the case of anonymous functions, we don't have one.

What is the closure function?

Closure functions are the anonymous functions that have access to their surroundings. In Go, the closure functions can have a state of their own and the state becomes isolated as we create new instances of the function.

Okay, now let's consider a very simple example of closure.

Example

Consider the code shown below.

package main
import (
   "fmt"
)
func main() {
   x := 22
   ff := func() {
      y := x / 2
      fmt.Println(y)
   }
   ff()
}

Output

If we run this code with the command go run main.go, we will get the following output printed on the terminal.

11

In the above code, we created a closure of the function named ff containing x. The anonymous function ff can access the value x directly, which in turn is the closure property.

Closures also provide a property called data isolation, in which the states of closure are unique when created which simply means that each closure has its own state.

Let's understand this concept with the help of an example.

Example

Consider the code shown below.

package main
import (
   "fmt"
)
func ff() func() int {
   z := 0
   return func() int {
      z += 100
      return z
   }
}
func main() {
   x := ff()
   y := ff()
   fmt.Println(x())
   fmt.Println(y())
   x()
   fmt.Println(x())
   fmt.Println(y())
}

Output

If we run this code with the command go run main.go, we will see the following output printed in the terminal.

100
100
300
200

We can notice the difference in the above output which clearly suggests that they contain different states.

raja
Updated on 21-Feb-2022 07:01:45

Advertisements