Handle typed nils
Handle typed nils
A nil interface has no dynamic type or value. An interface holding a typed nil pointer has a dynamic type, so the interface itself is not nil. This distinction matters when returning optional results or errors.
package main
import ( "fmt")
func main() { var p *int var x any = p var y any fmt.Println(p == nil, x == nil, y == nil) fmt.Printf("%T\n", x)}p is a nil pointer, but x holds the dynamic type *int and the nil pointer value. y has no dynamic type. Comparing x with nil tests the interface itself, not whether its dynamic value is a nil pointer.
Expected output:
true false true*intReturn a genuinely nil error
package main
import ( "fmt")
type Problem struct{}
func (*Problem) Error() string { return "problem" }func bad() error { var p *Problem; return p }func good(fail bool) error { if fail { return &Problem{} } return nil}func main() { fmt.Println(bad() == nil, good(false) == nil, good(true) == nil)}error is a built-in interface requiring Error() string. bad returns a typed nil pointer as an interface, which callers see as non-nil. good returns literal nil on success. A pointer-receiver method may explicitly handle nil, but one that dereferences a nil receiver panics.
Expected output:
false true falseTry it locally
Define Warning implementing error with a pointer receiver. Write check(ok bool) error returning nil when ok is true and &Warning{} otherwise. Print whether each result is nil.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Interfaces 06: Handle typed nils
Check the lesson objective before moving on.
Is any((*int)(nil)) equal to nil?
What should a successful error-returning function return?