Sobes.tech
Senior

When is a deferred function called? When exiting a local block, when exiting a function, or when the application terminates?

sobes.tech AI

Answer from AI

In Go, a deferred function declared with defer is called when exiting the function in which it was declared. This happens regardless of how the exit occurs — normal completion, error return, or panic.

Important: defer does not trigger when exiting a local block (for example, from a loop or conditional statement), only when exiting the entire function. Also, defer does not wait for the entire application to finish; it executes immediately upon the function's completion.

Example:

func example() {
    defer fmt.Println("deferred call")
    fmt.Println("function body")
}

// When calling example(), first "function body" will be printed, then "deferred call" upon exiting example.
When is a deferred function called? When exiting a… - sobes.tech