Consider the following Go code snippet. What will it print when run?
package main import "fmt" func main() { defer fmt.Println("First") defer fmt.Println("Second") defer fmt.Println("Third") fmt.Println("Start") }
Remember that deferred functions are executed in last-in, first-out order after the surrounding function returns.
The program first prints "Start" immediately. Then, when main returns, deferred calls run in reverse order: "Third", "Second", then "First".
What will this Go program print?
package main import "fmt" func main() { x := 0 defer fmt.Println(x) x = 5 defer fmt.Println(x) x = 10 }
Deferred function arguments are evaluated when the defer statement executes, not when the function runs.
The first defer captures x=0, but the argument is evaluated immediately, so it prints 0. The second defer captures x=5. But actually, in Go, the arguments are evaluated immediately, so the first defer prints 0, second prints 5. However, the order of execution is last-in, first-out, so output is 5 then 0.
Correction: The first defer prints 0, second prints 5, but they run in reverse order, so output is 5 then 0.
Analyze this code and select the correct output.
package main import "fmt" func main() { x := 1 defer func() { fmt.Println(x) }() x = 2 defer func(x int) { fmt.Println(x) }(x) x = 3 }
Deferred anonymous functions without parameters capture variables by reference; those with parameters capture by value.
The first deferred function has no parameters and prints the current value of x when it runs, which is 3. The second deferred function takes x as a parameter, so it captures the value 2 at defer time. Deferred functions run in reverse order, so output is 2 then 3.
What happens when you run this Go program?
package main import "fmt" func main() { defer fmt.Println("A") defer fmt.Println("B") panic("error") defer fmt.Println("C") }
Deferred functions run even if a panic occurs, but only those deferred before the panic.
The panic stops execution immediately after it runs. Deferred calls before panic run in reverse order: "B" then "A". The defer after panic is never reached. Then the panic message is printed.
Consider this Go function. What is the value of x printed at the end?
package main import "fmt" func main() { x := 0 defer func() { x += 1 fmt.Println("defer1:", x) }() defer func() { x += 2 fmt.Println("defer2:", x) }() x = 5 fmt.Println("main:", x) }
Deferred functions run in reverse order and modify the same variable x.
First, main prints x=5. Then deferred functions run in reverse order:
- defer2 adds 2 to x (5+2=7) and prints "defer2: 7"
- defer1 adds 1 to x (7+1=8) and prints "defer1: 8"