Init and Defer Keyword in Golang
Overview
In the Go language, init is a reserved keyword used for special purposes. Defer on other hand is a keyword that delays the execution of a function. In this article, we will cover all about Init and Defer statement in golang.
What is the Init Keyword?
The init() is a function that is similar to the main function of the Go language. This function does not take any argument as a parameter nor does it return anything. It is present in every package of golang and is called when any package in golang is initialized. This method is declared implicitly and hence cannot be declared from anywhere and is executed in the same order as mentioned. This function can be created anywhere in the program and is called in lexical file name order also known as alphabetical order. The main function of init() is to initialize a global variable that cannot be initialized in the global context.
When to Use Defer in Golang
Now that we know what is init function is all about, let’s try to understand when to use the init function in golang. It is used when we have to initialize or execute something right before the main function is executed. The typical use of the init function is while importing the packages. Unlike the main function, there can be one or more init functions. It is however optional to use the init function. It is mainly used for initialization and setting up the program environment.
Example of Init
Go Program to Illustrate the Concept of init() Function
Output:
Explanation:
In this example, the init function is initialized with a print statement that says “welcome to the init function”. After this, there is one more init function that prints “hello” and then starts the main function. As seen from the output, the functions are executed in the order in which they are initialized. The init function gets executed first following the second init function and the main function.
How Does Multiple Init Work?
The multiple init works the same way as any other function would work. In golang, if there are multiple init in the same program then they are executed in the order in which they were defined. This can be concluded from the example given below.
Example of Multiple Init
Go Program to Illustrate the Concept of init() Function
Output:
Explanation:
In this example, the order in which the init function is executed is the same as that mentioned in the code. This can be seen from the output.
What is a Defer Keyword and Why It Is Required?
Defer in golang is mainly used when the execution of the function is to be delayed. The defer function instantly evaluates the argument but doesn't execute until the functions that are nearby return.
Syntax
The syntax for creating a defer function is as follows:
Important Points
Here are a few important points that are to be considered in golang for defer keyword:
- Multiple defer statements are allowed in the same program in golang and are executed in LIFO that is, the last in, first out manner as depicted in the above example.
- The arguments in defer statement are evaluated when the defer statement is executed instead of when it is called.
- The defer statements are generally used for ensuring that the files are closed properly when not in use or close the channel.
Go Program to Illustrate the Concept of the Defer Statement
Go program to illustrate the concept of the defer statement
Output:
Explanation:
In this example, two functions mul() and show() are created. However, the show() function is already called in the main function but the mul() function is been called in two ways. In this first call, the mul() function is called normally without using defer keyword, like mul(2,9) which gives output as 18. The second way of calling the mul() function is by using the defer keyword, like defer mul(3,3) which gives output as 9.
Go Program to Illustrate Multiple defer Statements, to illustrate the LIFO policy
Output:
Explanation:
In this example, the defer keyword is used before the function add which means the other functions near it would be executed and the order of execution order of the function would be the same as mentioned in the code. Hence, in this example, the control or the flow of the code starts with the first defer statement. According to the definition, the defer function executes functions around itself, and hence the second defer function which is add(10,20) is executed. As soon as the control goes to the next defer function, the first function is executed which is add(3,5), and hence the output is 8.
Using Defer to Clean Up Resources
Using the defer in golang for cleaning up the resource in golang is common. To understand how it works, let’s take an example.
In this example, a string is written to a file without using the defer statement for the clean-up. Here the function call write creates a file. If an error is found then it will either return the error or exit the function. Finally, then the function returns nil to make the user know that the function has been executed without any error. The code works fine but there is still a bug in this code. If io.WriteString fails then the function will return without even closing the file which will lead to the file releasing back to the system resource. However, this problem can be resolved by adding the file.Close() statement.
But instead of adding a second call to the function, we can simply use defer statement. This is done to ensure that regardless of any branch that is taken into execution, the function is always closed. This is the code using defer keyword.
This is how by using the defer keyword, we ensure the resources are cleaned up properly.
Conclusion
-
In the Go language, init is a reserved keyword used for special purposes. Defer on other hand is a keyword that delays the execution of a function.
-
The init() is a function that is similar to the main function of the Go language. This function does not take any argument as a parameter nor does it return anything. It is present in every package of golang and is called when any package in golang is initialized.
-
The multiple init works the same way as any other function would work. In golang, if there are multiple init in the same program then they are executed in the order in which they were defined.
-
In golang, the defer keyword is mainly used when the execution of the function is to be delayed. The defer function instantly evaluates the argument but doesn't execute until the functions that are nearby return.
-
The syntax for defer is as follows:
-
Multiple defer statements are allowed in the same program in golang and are executed in LIFO.
-
The defer statements are generally used for ensuring that the files are closed properly when not in use or close the channel.
-
The arguments in defer statement are evaluated when the defer statement is executed instead of when it is called.