Golang / GoLang Basics Interview Questions
What is the 'typed nil' trap in Go and why does 'if err != nil' sometimes fail?
An interface value in Go has two components: a dynamic type and a dynamic value. An interface is nil only when BOTH are nil. A common mistake is returning a typed nil pointer as an error — the interface has a type component set, so it is NOT nil even though the pointer value is nil.
// The trap: returning a *MyError that is nil as an error interface
type MyError struct{ Code int }
func (e *MyError) Error() string { return fmt.Sprintf("error %d", e.Code) }
func riskyOperation(succeed bool) error {
var err *MyError // err is a nil *MyError pointer
if !succeed {
err = &MyError{Code: 404}
}
return err // BUG: returns interface{type=*MyError, value=nil}
// This interface is NOT nil!
}
result := riskyOperation(true) // supposed to succeed
if result != nil { // UNEXPECTED: true! Interface is non-nil.
fmt.Println("error:", result) // prints: error 0
}
// FIX: return bare nil, not a typed nil pointer
func safeOperation(succeed bool) error {
if !succeed {
return &MyError{Code: 404}
}
return nil // correct: returns a nil interface, not a *MyError nil
}
// Verify the fix
result2 := safeOperation(true)
fmt.Println(result2 == nil) // true — correct!
// Rule: functions returning an error interface should NEVER return
// a concrete typed pointer that might be nil. Always return bare nil.
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...
