Junior — Middle
How is the sequential execution of multiple deferred tasks (defer) performed?
sobes.tech AI
Answer from AI
In Go, the defer keyword is used to schedule a function call to be executed after the surrounding function completes. If there are multiple defer statements in a function, they are executed in last-in-first-out order — that is, in reverse order of their declaration.
Example:
func example() {
defer fmt.Println("first deferred")
defer fmt.Println("second deferred")
fmt.Println("function execution")
}
The output will be:
function execution
second deferred
first deferred
Thus, multiple deferred tasks are executed sequentially in reverse order of their declaration.