Bird
Raised Fist0
Goprogramming~10 mins

Why defer is used in Go - Visual Breakdown

Choose your learning style10 modes available
Concept Flow - Why defer is used
Start function
↓
Execute code before defer
↓
Register defer statement
↓
Execute remaining code
↓
Function about to return
↓
Run deferred calls in LIFO order
↓
Function returns
The function runs normally, but defer statements are saved and run just before the function returns, in reverse order.
Execution Sample
Go
func example() {
    defer fmt.Println("deferred call")
    fmt.Println("normal call")
}
This code prints "normal call" first, then "deferred call" after the function finishes.
Execution Table
StepActionOutputDeferred Calls Stack
1Start function example()[]
2Register defer fmt.Println("deferred call")[fmt.Println("deferred call")]
3Execute fmt.Println("normal call")normal call[fmt.Println("deferred call")]
4Function about to return, run deferred callsdeferred call[]
5Function returns[]
💡 Function ends after running deferred calls in last-in-first-out order
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
Deferred Calls Stack[][fmt.Println("deferred call")][fmt.Println("deferred call")][][]
Key Moments - 2 Insights
Why does the deferred call run after the normal print statement?
Because deferred calls are saved when registered and only run after the function finishes, as shown in execution_table step 4.
What happens if there are multiple defer statements?
They run in last-in-first-out order just before the function returns, meaning the last defer registered runs first.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is printed at step 3?
Adeferred call
Bnothing
Cnormal call
Dfunction returns
💡 Hint
Check the Output column at step 3 in the execution_table.
At which step are deferred calls executed?
AStep 3
BStep 4
CStep 2
DStep 5
💡 Hint
Look at the Action and Output columns in execution_table for when deferred calls run.
If we add another defer before the existing one, how does the Deferred Calls Stack change after step 2?
AIt contains both defers but the last added is on top
BIt contains both defers in order of registration
CIt contains only the first defer
DIt becomes empty
💡 Hint
Deferred calls run in last-in-first-out order, so the stack grows with newest on top.
Concept Snapshot
defer schedules a function call to run after the current function finishes.
Deferred calls run in last-in-first-out order just before return.
Use defer to clean up resources like files or locks.
Deferred calls run even if the function panics.
Syntax: defer functionCall()
Full Transcript
In Go, defer is used to delay a function call until the surrounding function finishes. When you write defer before a function call, Go saves that call and runs it after the current function returns. This is useful for cleanup tasks like closing files or unlocking resources. Deferred calls run in reverse order if there are multiple. For example, if you defer printing a message, the normal code runs first, then the deferred print happens last. This ensures important cleanup code always runs, even if the function exits early or due to an error.

Practice

(1/5)
1. What is the main purpose of using defer in Go?
easy
A. To create a new goroutine
B. To run a function immediately
C. To delay a function call until the surrounding function finishes
D. To declare a variable

Solution

  1. Step 1: Understand the behavior of defer

    The defer keyword postpones the execution of a function until the surrounding function returns.
  2. Step 2: Compare options with this behavior

    Only To delay a function call until the surrounding function finishes correctly describes this delaying behavior, while others describe unrelated actions.
  3. Final Answer:

    To delay a function call until the surrounding function finishes -> Option C
  4. Quick Check:

    Defer delays function calls = A [OK]
Hint: Defer means 'do later' when function ends [OK]
Common Mistakes:
  • Thinking defer runs function immediately
  • Confusing defer with goroutine creation
  • Assuming defer declares variables
2. Which of the following is the correct syntax to defer a function call cleanup() in Go?
easy
A. defer cleanup()
B. defer = cleanup()
C. defer: cleanup()
D. defer -> cleanup()

Solution

  1. Step 1: Recall Go's defer syntax

    The correct syntax is the keyword defer followed by the function call without any assignment or punctuation.
  2. Step 2: Check each option

    Only defer cleanup() matches the correct syntax. Others use invalid symbols or assignment.
  3. Final Answer:

    defer cleanup() -> Option A
  4. Quick Check:

    Defer syntax is 'defer function()' = A [OK]
Hint: Defer always followed by function call without extra symbols [OK]
Common Mistakes:
  • Adding '=' after defer
  • Using ':' or '->' instead of space
  • Omitting parentheses on function call
3. What will be 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\nSecond\nFirst
B. Second\nFirst\nThird
C. First\nSecond\nThird
D. Third\nFirst\nSecond

Solution

  1. Step 1: Identify the order of deferred calls

    Deferred calls run after the surrounding function ends, in reverse order of their defer statements. So "Second" runs before "First".
  2. Step 2: Trace the print statements

    "Third" prints immediately, then deferred prints run: "Second", then "First".
  3. Final Answer:

    Third\nSecond\nFirst -> Option A
  4. Quick Check:

    Deferred calls run last in reverse order = C [OK]
Hint: Deferred calls run last, in reverse order [OK]
Common Mistakes:
  • Assuming deferred calls run in order declared
  • Thinking deferred calls run immediately
  • Mixing up print order
4. Identify the error in this Go code snippet:
func process() {
    defer close(file)
    file, err := os.Open("data.txt")
    if err != nil {
        return
    }
    // process file
}
medium
A. File is closed twice due to defer and explicit close
B. Defer is used before file is assigned, causing a compile error
C. Defer cannot be used with file operations
D. No error, code works fine

Solution

  1. Step 1: Analyze the order of statements

    The defer statement tries to close file before file is assigned by os.Open. This causes a compile error because file is undefined at defer time.
  2. Step 2: Understand defer evaluation timing

    Arguments to deferred functions are evaluated immediately, so file must be assigned before defer.
  3. Final Answer:

    Defer is used before file is assigned, causing a compile error -> Option B
  4. Quick Check:

    Defer arguments evaluated immediately = B [OK]
Hint: Defer arguments evaluated immediately, assign variables first [OK]
Common Mistakes:
  • Placing defer before variable assignment
  • Thinking defer delays argument evaluation
  • Assuming defer can't be used with files
5. You want to open multiple files and ensure all are closed properly even if an error occurs. Which approach using defer is best?
func openFiles() {
    f1, _ := os.Open("file1.txt")
    f2, _ := os.Open("file2.txt")
    // What is the best way to defer closing these files?
}
hard
A. Use defer only for the last file opened
B. Defer closing both files together at the end of the function
C. Close files manually without defer
D. Defer closing each file immediately after opening it

Solution

  1. Step 1: Understand resource management with defer

    Deferring the close immediately after opening each file ensures each file is closed properly even if the function returns early.
  2. Step 2: Compare options

    Defer closing each file immediately after opening it defers closing right after opening, which is safe. Defer closing both files together at the end of the function delays both closes until the end, risking leaks if errors occur. Close files manually without defer is error-prone. Use defer only for the last file opened misses closing one file.
  3. Final Answer:

    Defer closing each file immediately after opening it -> Option D
  4. Quick Check:

    Defer resource cleanup immediately after acquisition = D [OK]
Hint: Defer cleanup right after resource acquisition [OK]
Common Mistakes:
  • Deferring all closes at once at the end
  • Not deferring close for every opened file
  • Closing files manually without defer
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