0
0
Goprogramming~20 mins

Why defer is used in Go - Challenge Your Understanding

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Go Defer Mastery
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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")
}
A
Second
First
Third
B
First
Second
Third
C
Third
First
Second
D
Second
Third
First
Attempts:
2 left
💡 Hint
Remember defer calls run after the surrounding function finishes, in reverse order.
🧠 Conceptual
intermediate
1:30remaining
Why use defer in Go functions?
Which of these best explains why Go programmers use defer?
ATo run a function immediately before the current line
BTo delay execution of a function until the surrounding function returns
CTo run a function only if an error occurs
DTo run a function repeatedly in a loop
Attempts:
2 left
💡 Hint
Think about when deferred functions run compared to normal calls.
🔧 Debug
advanced
2: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")
}
Apanic: runtime error: invalid memory address or nil pointer dereference
Bcompile error: missing return statement
Cno error, prints "File opened"
Druntime error: index out of range
Attempts:
2 left
💡 Hint
What happens if os.Open fails and returns nil for the file?
Predict Output
advanced
2: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)
    }
}
A123
B111
C321
DError: cannot use i in defer
Attempts:
2 left
💡 Hint
Deferred calls run in last-in, first-out order.
🧠 Conceptual
expert
3: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?
AIt ensures cleanup code runs even if the function returns early or panics
BIt speeds up the execution of resource allocation
CIt allows resources to be shared between goroutines automatically
DIt prevents any errors from occurring during resource use
Attempts:
2 left
💡 Hint
Think about functions that might exit in many ways.