Golang defer
What is defer?
The defer keyword in Golang is a way to execute a function after the current function has finished. This is regardless of whether the surrounding function completes execution typically or with a panic. This can be useful for cleaning up resources, such as closing a file or a network connection, that need to be closed regardless of how the surrounding function completes execution.
How to use defer
Defer is used by calling the defer
keyword before a function call. For example:
This will print:
Example opening a file
Defer is useful for things like closing a file or a WebSocket connection. For example:
The order of defer
Defer is based on a stack. Meaning that it implements a last in first out (LIFO) order. So if multiple defer statements are used within a function, they will be executed in reverse order. This can be useful for logically structuring the clean-up code.
Defer in a stack
For example:
Lifo In action
The output of this will be:
In this scenario, the !
is the last to enter into the stack and the first to be executed. This also applies to other functions in the stack.
Defer in a for loop
When using defer in a for loop, for each iteration, the defer function will be added to the stack. After the loop has finished executing, the defer functions will then be executed in reverse order. For example:
This will print:
Defer in an if statement
The behavior of defer in an if statement is similar to that of any other execution occurring in an if statement. The function will only be deferred if the condition is true. For example:
This will print:
Conclusion
In this article, we looked at defer in Golang. We looked at how to use defer, the order of defer, defer in a for loop, and defer in an if statement. We also looked at some examples of how to use defer.