In Go language, defer is a very useful keyword used for deferring the execution of functions, typically employed for performing cleanup or resource release operations before a function returns.
A defer statement pushes the function call that should be deferred onto a stack and executes these deferred function calls in a last-in, first-out (LIFO) order just before the current function returns.
Here are some important features and uses of defer:
Deferred Execution: Using the defer keyword ensures that a function call is executed before the containing function returns, whether it returns normally or due to an error.
Resource Cleanup: Common use cases include closing files, releasing locks, closing database connections, and other cleanup operations to prevent resource leaks.
Parameter Evaluation: The parameters in a defer statement are evaluated when the defer statement is executed, not when the function returns.
Here are some examples demonstrating the use of defer:
1 | package main |
In the above examples, defer statements are used to ensure the file is closed before main returns, log the execution time of the function, and execute multiple defer statements in a last-in, first-out order.
defer is a powerful tool in Go that can help you write safer and cleaner code, ensuring proper resource release and consistency.”