Senior
What is defer in Go? What will the code with two defer statements output?
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 completes, but before it returns.
If there are multiple defer statements in a function, they are executed in the reverse order of their declaration (stack order).
Example:
package main
import "fmt"
func main() {
defer fmt.Println("First defer")
defer fmt.Println("Second defer")
fmt.Println("Main code")
}
The output will be:
Main code
Second defer
First defer
That is, the main code runs first, then the deferred calls are executed in reverse order.