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.
More Related questions...