Predict the output
What does f() print?
func f() {
defer { print("1") }
defer { print("2") }
print("3")
}
f()Hint 1 of 1
Defers behave like a stack.
Choose an answer, then open Show answer below to check it.
Show answer
Answer: C 3 2 1
Correct. The body runs, then the defers run in reverse order.
Why not the others?
- A 1 2 3. Deferred blocks wait until the scope exits.
- B 3 1 2. Defers run last-in, first-out.
- D 3. Both defers run when the function returns.