![]() |
VOOZH | about |
In Go language, defer statements delay the execution of the function or method or an anonymous method until the nearby functions returns. In other words, defer function or method call arguments evaluate instantly, but they don't execute until the nearby functions returns. You can create a deferred method, or function, or anonymous function by using the defer keyword.
Syntax:
// Function
defer func func_name(parameter_list Type)return_type{
// Code
}
// Method
defer func (receiver Type) method_name(parameter_list){
// Code
}
defer func (parameter_list)(return_type){
// code
}()
Important Points:
Let us discuss this concept with the help of an example:
Example 1:
Output:
Result: 1035 Hello!, GeeksforGeeks Result: 1288
Explanation: In the above example we have two functions named mul() and show(). Where show() function is called normally in the main() function, mul() function is called in two different ways:
Example 2:
Output:
Start Result: 20 Result: 90 End