Defer
The defer keyword allows you to schedule a function call to run immediately before its enclosing function returns.
Usage: Cleanup
defer is primarily used for cleaning up resources like closing database connections or closing files, ensuring they are handled regardless of which return statement is hit.
func processFile(filename string) {
f, _ := os.Open(filename)
defer f.Close() // Runs at the very end of processFile
// ... perform operations on the file
if errorCondition {
return // f.Close() still runs here!
}
}
Multiple Defers (LIFO)
If you use multiple defer statements in a single function, they are executed in Last-In, First-Out (LIFO) order. The last deferred call is the first one to run.
func multiDefer() {
defer fmt.Println("first")
defer fmt.Println("second")
}
// Prints:
// second
// first
Argument Evaluation
The arguments to a deferred function are evaluated immediately, but the function call itself is delayed.