Defer is a powerful feature in Go, which is similar to "finally" in other languages.
func main() {
defer fmt.Println("Hello, World!")
fmt.Println("Hello")
}
The deferred call's arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.
Defer works as a stack, deferred calls are executed in last-in-first-out order. (LIFO)
Defers are even executed when a panic occours
Use cases
- Cleaning up resources after an operations. E. g. closing files
- Measuring performance of a function
- Recovering from panics, as defer functions are still run in case of error. See: panic & recover
Next chapter: Errors