0
0
Goprogramming~5 mins

Defer execution order in Go - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the defer keyword do in Go?

The defer keyword schedules a function call to run after the surrounding function finishes, just before it returns.

Click to reveal answer
beginner
In what order are multiple deferred functions executed in Go?

Deferred functions are executed in last-in, first-out (LIFO) order. The last deferred function runs first.

Click to reveal answer
beginner
Consider this code snippet:<br>
func example() {
  defer fmt.Println("first")
  defer fmt.Println("second")
  fmt.Println("middle")
}
<br>What is the output?

The output will be:<br>middle<br>second<br>first

Because deferred calls run after the function ends, in reverse order.

Click to reveal answer
intermediate
Why is defer useful for resource management in Go?

Defer helps ensure resources like files or locks are released properly, even if the function returns early or an error occurs.

Click to reveal answer
intermediate
Can deferred functions modify named return values in Go?

Yes, deferred functions can modify named return values because they run just before the function returns.

Click to reveal answer
What happens when multiple defer statements are used in a Go function?
AThey execute in the order they appear.
BOnly the first defer executes.
CThey execute in reverse order (last deferred runs first).
DThey execute simultaneously.
When exactly do deferred functions run in Go?
AImmediately when deferred.
BAfter the surrounding function returns, before it actually returns to the caller.
CAt the start of the function.
DOnly if the function panics.
Which of these is a common use case for defer in Go?
AClosing files or releasing locks.
BOpening network connections.
CStarting goroutines.
DDeclaring variables.
If a deferred function modifies a named return variable, when does that modification take effect?
ABefore the function starts.
BAfter the function returns to the caller.
CIt never takes effect.
DJust before the function returns to the caller.
What will this Go code print?<br>
func f() {
  defer fmt.Println(1)
  defer fmt.Println(2)
  defer fmt.Println(3)
}

f()
A3 2 1
B1 2 3
C1 3 2
D2 3 1
Explain how the defer keyword controls the execution order of deferred functions in Go.
Think about a stack of plates where the last plate placed is the first one taken.
You got /3 concepts.
    Describe a practical example where using defer improves code safety or clarity.
    Imagine you open a file and want to make sure it always closes.
    You got /4 concepts.