Golang / GoLang Basics Interview Questions
How do defer, panic, and recover work together in Go?
defer schedules a function call to run when the surrounding function returns — regardless of how it returns (normally, via error, or via panic). It is Go's idiomatic resource-cleanup mechanism. panic stops normal execution; recover catches it inside a deferred function.
// defer — executes when surrounding function returns
func processFile(path string) error {
f, err := os.Open(path)
if err != nil { return err }
defer f.Close() // ALWAYS runs, even if function returns early
// process file...
return nil
}
// Multiple defers: LIFO order (last-in, first-out)
func demo() {
defer fmt.Println("3rd") // runs first (LIFO)
defer fmt.Println("2nd")
defer fmt.Println("1st") // runs last? NO — runs first!
// Output order: 1st, 2nd, 3rd — wait, no:
// ACTUAL order: 3rd → 2nd → 1st (LIFO!)
}
// Defer argument evaluation: immediate, not deferred!
x := 5
defer fmt.Println(x) // prints 5 — x evaluated NOW
x = 10 // too late to affect the defer
// panic — signals an unrecoverable error
func mustPositive(n int) int {
if n <= 0 { panic(fmt.Sprintf("expected positive, got %d", n)) }
return n
}
// recover — catches a panic; ONLY useful inside defer
func safeDiv(a, b int) (result int, err error) {
defer func() {
if r := recover(); r != nil {
err = fmt.Errorf("recovered: %v", r)
}
}()
return a / b, nil // panics if b == 0
}
Invest now in Acorns!!! 🚀
Join Acorns and get your $5 bonus!
Acorns is a micro-investing app that automatically invests your "spare change" from daily purchases into diversified, expert-built portfolios of ETFs. It is designed for beginners, allowing you to start investing with as little as $5. The service automates saving and investing. Disclosure: I may receive a referral bonus.
Invest now!!! Get Free equity stock (US, UK only)!
Use Robinhood app to invest in stocks. It is safe and secure. Use the Referral link to claim your free stock when you sign up!.
The Robinhood app makes it easy to trade stocks, crypto and more.
Webull! Receive free stock by signing up using the link: Webull signup.
More Related questions...
