Challenge - 5 Problems
Go Defer Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this Go code using defer?
Look at this Go program. What will it print when run?
Go
package main import "fmt" func main() { defer fmt.Println("First") fmt.Println("Second") defer fmt.Println("Third") }
Attempts:
2 left
💡 Hint
Remember defer calls run after the surrounding function finishes, in reverse order.
✗ Incorrect
The deferred calls are stacked and executed after main ends. So "Second" prints first, then deferred calls print "Third" then "First".
🧠 Conceptual
intermediate1:30remaining
Why use defer in Go functions?
Which of these best explains why Go programmers use defer?
Attempts:
2 left
💡 Hint
Think about when deferred functions run compared to normal calls.
✗ Incorrect
Defer schedules a function to run after the current function finishes, useful for cleanup tasks like closing files.
🔧 Debug
advanced2:30remaining
What error occurs in this Go code using defer?
This Go code tries to defer closing a file. What error will it cause?
Go
package main import ( "fmt" "os" ) func main() { f, err := os.Open("nofile.txt") if err != nil { fmt.Println("Error opening file") return } defer f.Close() fmt.Println("File opened") }
Attempts:
2 left
💡 Hint
What happens if os.Open fails and returns nil for the file?
✗ Incorrect
If os.Open fails, f is nil but defer f.Close() still runs, causing a nil pointer dereference panic.
❓ Predict Output
advanced2:00remaining
What is the output order of deferred calls in this Go program?
Predict the output of this Go program with multiple defers.
Go
package main import "fmt" func main() { for i := 1; i <= 3; i++ { defer fmt.Print(i) } }
Attempts:
2 left
💡 Hint
Deferred calls run in last-in, first-out order.
✗ Incorrect
The loop defers printing 1, then 2, then 3. They run in reverse order: 3 2 1.
🧠 Conceptual
expert3:00remaining
What is a key benefit of using defer for resource management in Go?
Why is defer especially useful for managing resources like files or locks in Go?
Attempts:
2 left
💡 Hint
Think about functions that might exit in many ways.
✗ Incorrect
Defer guarantees cleanup code runs no matter how the function exits, preventing resource leaks.