Closures in Golang

Learn via video courses
Topics Covered

Overview

In this article, we will learn about Closure, How and why closure is introduced in Golang.

Introduction

Before we learn about closure, let's first try to understand what is Anonymous Functions with its example.

What are Anonymous Functions?

Anonymous Functions are those which do not have a function name or a function without a name.

For Example, Let's first see the regular function:

You can call it like this:

Output:

Run the Code!

Now, let's try to convert this Regular Function into Anonymous Function:

Output:

Run the code!

You can see that both are working perfectly fine! Anonymous functions are useful when you wish to define a function inline without having to name it. An anonymous function's benefit is that it does not need to be kept in a separate file. The usage of anonymous functions also minimizes the number of code files required for a program, which can significantly simplify programs.

Closure in Golang

Closure, is a form from Anonymous Function that refers to variables specified outside of the function itself. It is equivalent to accessing global variables that existed before the function's declaration. It works similarly to a regular function and perform all the things perform by any function.

Following Syntax:

Let's try to understand with some examples:

Note : Closure work as a nested function which helps it to access the outside function's variables no matter if the outer function is closed or not.

  • In the above code, we created the function called message() that returns a nested anonymous function and whenever we try to call this function in our main function by assigning it to some variable in our case mssg, it will destroy the text at this time and outer function will be completed.
  • But, when we call the fmt.Println(mssg()) we are able to access the text variable.
  • Because of nested function now serves as a closure, it closes the external scope variable within its scope even after the outer function is completed.

Output:

Run the code!

Basic Example to print even numbers:

Output:

Run the code! In the above code, the outer function executes the calculate() and returns a closure to the even number. This allows us to access the num variable of calculate() even after completing the outer function.

Another Example with counter:

Output:

Run the code!

  • In the above code, The closure refers to the variable Scaler even after the newCounter() function has run, but no other code outside of the newCounter() method has access to this variable.
  • That's how data persistency between function calls is handled while simultaneously isolating the data from other codes.

Closures to Enable Data Isolation

  • Closure is independent of other closures and changes won't affect each other.
  • This feature helps us to accomplish the data isolation or makes each one of them have its state.

For Example:

Output:

Run the code!

In the above code, a and b seem to be in isolated states. This becomes clear when we call a function that triggers the state to change. This is why closures are so useful.

Another Example:

Output:

Run the Code!

  • In the above code, shownum function returns an anonymous function that increments the number by 1.
  • In the main function we are calling shownum using num1 and num2, we first call the closure function using num1 which increments 3 times 1,2,3, and then again second call the closure function using num2 which increases by 1,2 and the main point to notice that the number is not continuing after 3 rather it again starts from 1 which shows the data isolation feature implemented in the code using a closure.

Advantages of Closures

Here are some advantages of closures:

  • They allow you to correlate variables with an execution context.
  • Variables in closures can assist you in preserving a state for later use.
  • They are responsible for data encapsulation.
  • They facilitate the removal of duplicate code.
  • They also help in the maintenance of generic code.

Disadvantages of Closures

  • Disadvantages can be described as if there are too many closures included in the code it may cause to slow down your application.
  • Another problem with closure is that there is no garbage collection for the variables specified inside a closure.

When to Use Closure?

  • It is good if the calculation is going simply added inside the function and it will also help in saving memory for us because every variable takes some space in the programming language but as we can see we are not giving any name to the closure function.
  • Therefore, it will not occupy any space until it gets a call for performing its responsibility and calculations if we want then we can allocate the closure function to any variable and call the function with the variable name.
  • Go closure is also useful when we want to create middleware which is commonly used for logging, error handling, or compression of data.
  • It allows us to handle several minor calculations without having to create a function for each one.

Conclusion

  • In this article, we saw An anonymous function is a function without a name.
  • We also got to know about what is closure in golang. A closure is a function value that refers to variables outside of the scope of its own function body. A closure can survive the scope of the function that defines it. This means it has access to variables that are outside of its scope.
  • They also help you to write clean and generic code.