📖 Scenario: Imagine you are writing a Go program that needs to clean up resources in a specific order after some operations. You want to learn how defer statements work and how their execution order is managed.
🎯 Goal: Build a Go program that uses multiple defer statements and prints messages to show the order in which deferred functions execute.
📋 What You'll Learn
Create a main function
Use multiple defer statements with print messages
Understand and demonstrate the LIFO (last-in, first-out) order of defer execution
Print the messages to show the order clearly
💡 Why This Matters
🌍 Real World
In real programs, defer is used to ensure resources like files or network connections are properly closed even if errors occur.
💼 Career
Understanding defer is important for writing clean, safe Go code especially in backend development, system programming, and cloud services.
Progress0 / 4 steps
1
Create the main function and initial print
Write a main function in Go that prints "Start of main".
Go
Hint
Use func main() to define the main function and println to print the message.
2
Add two defer statements with print messages
Inside the main function, add two defer statements that print "First defer" and "Second defer" respectively.
Go
Hint
Use defer println("message") to add deferred print statements.
3
Add a final print statement after defer statements
After the two defer statements, add a print statement that prints "End of main" inside the main function.
Go
Hint
Just add println("End of main") after the defer statements.
4
Run the program and observe the output
Run the program and print the output to see the order of execution of the print statements and deferred functions.
Go
Hint
Run the program using go run and observe that deferred functions run in reverse order.
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
Step 1: Understand defer behavior
In Go, deferred functions are postponed until the surrounding function returns.
Step 2: Execution order of deferred calls
Deferred calls run in reverse order of their appearance, like a stack (last-in, first-out).
Final Answer:
Deferred calls execute in last-in, first-out order when the function returns. -> Option A
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
Step 1: Recall defer syntax
The keyword defer is followed directly by the function call without assignment or parentheses around defer.
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
Step 1: Understand expected output order
"D" should print first immediately, then deferred calls print "C", "B", "A" in reverse order.
Step 2: Identify cause of unexpected output
If "D" is missing or not printed before defers, output order changes unexpectedly.
Final Answer:
The function does not call fmt.Println("D") before defers. -> Option A
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
Step 1: Understand defer closing order
Deferred calls run last-in, first-out, so the last deferred closes first.
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.
Final Answer:
defer file1.Close()
defer file2.Close()
defer file3.Close() -> Option D
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 unknownstrongwhile earning +1 Grip toward your certificate.