Middle+
What is defer? How does it work? Is it called during a panic?
sobes.tech AI
Answer from AI
In Go, the keyword defer is used to call a function at a later time — it will be executed after the surrounding function finishes, regardless of how it ends (normally or with an error).
How defer works:
- When the
deferstatement is executed, the function is not called immediately but is placed on a stack of deferred calls. - After the function in which
deferwas declared finishes, all deferred functions are called in reverse order.
During a panic, deferred functions are still called, which allows, for example, to properly release resources or log errors before the program terminates.
Example:
func example() {
defer fmt.Println("Deferred call")
fmt.Println("Before panic")
panic("Something went wrong")
// The deferred call will execute even after a panic
}
In this example, "Deferred call" will be printed despite the panic.