Back to questions
JuniorTheoryCommon
What does the program print?
package main
import "fmt"
func main() {
x := 1
defer fmt.Print(x)
x++
defer fmt.Print(x)
x++
fmt.Print(x)
}321
- Expecting
333: the arguments of a deferred call are evaluated on thedeferline, so the two calls remember1and2, not the finalx. - Expecting
312: deferred calls run in reverse order, so the seconddefer, holding2, runs before the first one, holding1.
- How would you change the first
deferso that it prints the final value ofx? - What would the program print if both
deferlines came after the lastx++?