JuniorCodeCommonNot answered yet
What does defer do, and in what order do multiple deferred calls run?
Read the snippet below. Three defer statements are registered before the function body finishes.
Determine the order in which the lines are printed, and explain what defer does and in what order multiple deferred calls run.
func main() {
defer fmt.Println("one")
defer fmt.Println("two")
defer fmt.Println("three")
fmt.Println("body")
}
Predict the output.
defer schedules a call to run when the surrounding function returns. Multiple deferred calls run in LIFO order — last registered, first executed — so they print in reverse of registration order.
- ✗Expecting deferred calls to run in registration (FIFO) order rather than LIFO
- ✗Thinking
deferruns the call right away instead of at function return - ✗Believing the deferred call is skipped when the function panics
- →Does a deferred call still run if the function panics?
- →Where are pending deferred calls stored for a single goroutine?
What does this print?
package main
import "fmt"
func main() {
defer fmt.Println("one")
defer fmt.Println("two")
defer fmt.Println("three")
fmt.Println("body")
}
Output:
body
three
two
one
The body of main runs first. When the function returns, the deferred calls run in LIFO order: the last registered ("three") runs first, the first registered ("one") runs last. Deferred calls are pushed onto a stack tied to the current function call and fire as it exits — including on a panic.