📖 Scenario: Imagine you are writing a Go program that opens a file, reads some data, and then closes the file. You want to make sure the file is always closed properly, even if something goes wrong while reading.
🎯 Goal: You will learn how to use defer in Go to ensure a file is closed automatically at the right time, making your code safer and cleaner.
📋 What You'll Learn
Create a variable to open a file
Use defer to close the file
Read from the file
Print the read content
💡 Why This Matters
🌍 Real World
In real programs, resources like files or network connections must be closed properly to avoid problems. Using <code>defer</code> helps make sure this happens even if errors occur.
💼 Career
Understanding <code>defer</code> is important for writing safe and clean Go code, which is a valuable skill for backend development and systems programming jobs.
Progress0 / 4 steps
1
Open a file
Write code to open a file named example.txt using os.Open and assign it to a variable called file. Also handle the error by assigning it to err.
Go
Hint
Use os.Open("example.txt") and assign the results to file and err.
2
Use defer to close the file
Add a defer statement to call file.Close() right after opening the file to ensure it will be closed automatically when the function ends.
Go
Hint
Write defer file.Close() right after checking the error.
3
Read from the file
Create a byte slice called data with length 100. Use file.Read(data) to read from the file and assign the number of bytes read to n and error to err. Handle the error if it is not nil.
Go
Hint
Create data with make([]byte, 100) and read into it with file.Read(data).
4
Print the read content
Print the string version of the bytes read from the file using fmt.Println(string(data[:n])).
Go
Hint
Use fmt.Println(string(data[:n])) to print the content read.
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
Step 1: Understand the behavior of defer
The defer keyword postpones the execution of a function until the surrounding function returns.
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.
Final Answer:
To delay a function call until the surrounding function finishes -> Option C
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
Step 1: Recall Go's defer syntax
The correct syntax is the keyword defer followed by the function call without any assignment or punctuation.
Step 2: Check each option
Only defer cleanup() matches the correct syntax. Others use invalid symbols or assignment.
Final Answer:
defer cleanup() -> Option A
Quick Check:
Defer syntax is 'defer function()' = A [OK]
Hint: Defer always followed by function call without extra symbols [OK]
Deferred calls run after the surrounding function ends, in reverse order of their defer statements. So "Second" runs before "First".
Step 2: Trace the print statements
"Third" prints immediately, then deferred prints run: "Second", then "First".
Final Answer:
Third\nSecond\nFirst -> Option A
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
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.
Step 2: Understand defer evaluation timing
Arguments to deferred functions are evaluated immediately, so file must be assigned before defer.
Final Answer:
Defer is used before file is assigned, causing a compile error -> Option B
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
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.
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.
Final Answer:
Defer closing each file immediately after opening it -> Option D
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 unknownstrongwhile earning +1 Grip toward your certificate.