Senior
When is a deferred function called? (upon exiting a local block / upon exiting a function / upon application termination)
sobes.tech AI
Answer from AI
In Go, a deferred function declared with the defer keyword is called when the function in which it was declared exits. This happens regardless of how the function terminates — whether by normal return, panic, or other means.
Important:
deferexecutes upon exiting the entire function, not just a local block inside the function.- If
deferis declared inside a loop or block, it will still execute upon exiting the function.
Example:
func example() {
defer fmt.Println("Deferred function will execute upon exiting example")
fmt.Println("Inside the function")
}
Here, the deferred function will be called after example completes.