Bird
Raised Fist0
Goprogramming~10 mins

Defer execution order in Go - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Defer execution order
Start function
↓
Execute statements
↓
Encounter defer statement
↓
Store deferred call on stack
↓
Continue executing
↓
Function end reached
↓
Pop deferred calls from stack
↓
Execute deferred calls in LIFO order
↓
Function returns
When Go runs a function, deferred calls are saved and run last in reverse order, just before the function ends.
Execution Sample
Go
package main
import "fmt"

func main() {
  defer fmt.Println("First")
  defer fmt.Println("Second")
  fmt.Println("Hello")
}
This code prints "Hello" first, then deferred prints in reverse order: "Second", then "First".
Execution Table
StepActionDeferred StackOutput
1Start main function[]
2defer fmt.Println("First")[First]
3defer fmt.Println("Second")[First, Second]
4fmt.Println("Hello")[First, Second]Hello
5End of main reached, start deferred calls[First, Second]Hello
6Pop and execute deferred call: Second[First]Hello Second
7Pop and execute deferred call: First[]Hello Second First
8main function returns[]Hello Second First
💡 Function ends, all deferred calls executed in last-in-first-out order.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 6After Step 7Final
Deferred Stack[][First][First, Second][First][][]
Output"""""""Hello Second ""Hello Second First ""Hello Second First "
Key Moments - 2 Insights
Why do deferred calls run after the function's main code finishes?
Deferred calls are stored on a stack and only run after the function reaches its end, as shown in steps 5-8 in the execution_table.
Why does the last deferred call run first?
Deferred calls run in last-in-first-out order, so the most recently deferred call executes first, as seen in steps 6 and 7.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the deferred stack after step 3?
A[Second, First]
B[First, Second]
C[First]
D[]
💡 Hint
Check the 'Deferred Stack' column at step 3 in the execution_table.
At which step does the output first show "Second"?
AStep 6
BStep 4
CStep 7
DStep 8
💡 Hint
Look at the 'Output' column in the execution_table and find when "Second" appears.
If we add another defer after step 3, where would it appear in the deferred stack?
AAt the bottom of the stack
BIt replaces the first deferred call
CAt the top of the stack
DIt runs immediately
💡 Hint
Deferred calls are pushed onto the stack; new defers go on top as shown in steps 2 and 3.
Concept Snapshot
Go's defer statements save calls to run later.
Deferred calls run after the function ends.
They run in reverse order (last-in-first-out).
Use defer to delay cleanup or final actions.
Deferred calls stack up and execute just before return.
Full Transcript
In Go, when you use defer, the function call is saved and runs only after the surrounding function finishes. Each defer adds a call to a stack. When the function ends, Go pops calls off this stack and runs them in reverse order. For example, if you defer printing "First" and then "Second", the program prints "Hello" first, then "Second", then "First". This happens because deferred calls run last-in-first-out. This helps with cleanup tasks that must happen after the main work is done.

Practice

(1/5)
1. What happens when multiple defer statements are used in a Go function?
easy
A. Deferred calls execute in last-in, first-out order when the function returns.
B. Deferred calls execute immediately when encountered.
C. Deferred calls execute in the order they appear in the code.
D. Deferred calls never execute automatically.

Solution

  1. Step 1: Understand defer behavior

    In Go, deferred functions are postponed until the surrounding function returns.
  2. Step 2: Execution order of deferred calls

    Deferred calls run in reverse order of their appearance, like a stack (last-in, first-out).
  3. Final Answer:

    Deferred calls execute in last-in, first-out order when the function returns. -> Option A
  4. Quick Check:

    Defer order = last-in, first-out [OK]
Hint: Remember: defer calls run backwards at function end [OK]
Common Mistakes:
  • Thinking defer calls run immediately
  • Assuming defer calls run in code order
  • Believing defer calls never run
2. Which of the following is the correct syntax to defer a function call in Go?
easy
A. defer() fmt.Println("Hello")
B. defer := fmt.Println("Hello")
C. defer fmt.Println("Hello")
D. defer call fmt.Println("Hello")

Solution

  1. Step 1: Recall defer syntax

    The keyword defer is followed directly by the function call without assignment or parentheses around defer.
  2. Step 2: Identify correct syntax

    defer fmt.Println("Hello") correctly uses defer fmt.Println("Hello"). Other options misuse defer syntax.
  3. Final Answer:

    defer fmt.Println("Hello") -> Option C
  4. Quick Check:

    defer + function call = correct syntax [OK]
Hint: Use 'defer' directly before function call without extra symbols [OK]
Common Mistakes:
  • Adding := after defer
  • Using parentheses after defer keyword
  • Writing extra words like 'call' after defer
3. What is the output of this Go program?
package main
import "fmt"
func main() {
    defer fmt.Println("First")
    defer fmt.Println("Second")
    fmt.Println("Third")
}
medium
A. Third First Second
B. Third Second First
C. First Second Third
D. Second First Third

Solution

  1. Step 1: Identify immediate and deferred prints

    "Third" is printed immediately. The two deferred prints run after main ends.
  2. Step 2: Determine deferred call order

    Deferred calls run last-in, first-out, so "Second" prints before "First".
  3. Final Answer:

    Third Second First -> Option B
  4. Quick Check:

    Immediate then deferred reverse order = Third, Second, First [OK]
Hint: Immediate prints first; deferred prints run backward after [OK]
Common Mistakes:
  • Assuming deferred prints run in code order
  • Thinking deferred prints run before immediate prints
  • Confusing the order of deferred calls
4. Consider this Go code snippet:
func example() {
    defer fmt.Println("A")
    defer fmt.Println("B")
    defer fmt.Println("C")
    fmt.Println("D")
}
If the output is not as expected, what is the likely mistake?
medium
A. The function does not call fmt.Println("D") before defers.
B. The deferred calls are not in reverse order.
C. The deferred calls are missing parentheses.
D. The deferred calls execute immediately, not at function end.

Solution

  1. Step 1: Understand expected output order

    "D" should print first immediately, then deferred calls print "C", "B", "A" in reverse order.
  2. Step 2: Identify cause of unexpected output

    If "D" is missing or not printed before defers, output order changes unexpectedly.
  3. Final Answer:

    The function does not call fmt.Println("D") before defers. -> Option A
  4. Quick Check:

    Immediate prints must run before deferred calls [OK]
Hint: Ensure immediate prints run before deferred calls [OK]
Common Mistakes:
  • Expecting deferred calls to run in code order
  • Forgetting to call immediate print before defers
  • Misunderstanding when deferred calls execute
5. You want to open three files in a Go function and ensure all are closed properly using defer. Which code snippet correctly closes the files in the right order?
hard
A. file1.Close() file2.Close() file3.Close()
B. defer file3.Close() defer file2.Close() defer file1.Close()
C. defer Close(file1) defer Close(file2) defer Close(file3)
D. defer file1.Close() defer file2.Close() defer file3.Close()

Solution

  1. Step 1: Understand defer closing order

    Deferred calls run last-in, first-out, so the last deferred closes first.
  2. Step 2: Apply to file closing

    Deferring file1.Close() first, then file2.Close(), then file3.Close() means file3 closes first, then file2, then file1, matching open order reversed.
  3. Final Answer:

    defer file1.Close() defer file2.Close() defer file3.Close() -> Option D
  4. Quick Check:

    Defer in open order closes files in reverse [OK]
Hint: Defer closes in reverse order of defer statements [OK]
Common Mistakes:
  • Deferring closes in reverse order of opening
  • Calling Close() immediately without defer
  • Using incorrect function calls for closing
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard