Introduction
A Go program uses many resources like open files, database handles and network connections when it is running. It is essential to close those resources to avoid exhausting them and allow other functions to utilise them. As a programmer, one must make sure to clean up the resources used and keep the code clean. The defer statements of Golang help carry out the above operations and is extremely useful.
Defer
Defer means to put off an event or action to a later time. The defer keyword does exactly this in Golang.
Syntax for using defer in a statement:
defer statement;
Syntax for using defer in functions:
defer func func_name(parameter_list Type)return_type{
// Code
}
defer func (receiver Type) method_name(parameter_list){
// Code
}
defer func (parameter_list)(return_type){
// Code
}()
Any statement that uses defer is postponed until the end of a function. After executing all statements in the function, the defer statement is executed. Let’s understand this using a simple example.
package main
import "fmt"
func main(){
defer fmt.Println("Line b")
fmt.Println("Line a")
}
Output:
Line a
Line b
The use of defer in the first line of the main function causes that statement to be postponed until the end of the function. Hence, it is executed in the last.
In practical applications, defer is used in functions to clean up its resources.
Here are a few key points to remember about the defer keyword.
-
The defer keyword allows the code execution in a LIFO order, last-in-first-out. This statement adds the function call following the defer keyword onto a stack. All of the calls on that stack are called when the function in which they were called returns.
-
The arguments to the deferred function are evaluated on execution and not its call.
-
The defer function will not be called when a call is made to it directly; rather, a call made to a statement next to the defer function can cause its execution.
-
The execution of a deferred function is delayed until the surrounding function returns.
- A deferred function will be executed even if the enclosing function terminates abruptly.
Example:
package main
import "fmt"
func calc(a, b int) int{
res := a * b
fmt.Println("Product: ", res)
return 0
}
func show(){
fmt.Println("The product of two numbers.")
}
func main(){
defer calc(23, 56)
show()
}
Output:
The product of two numbers.
Product: 60