Errors as language semantics
The predeclared `error` type and interface nil behavior are language semantics underneath Go's idiomatic error-handling style.
Canonical guidance
erroris a predeclared interface type- an interface value is nil only when both its dynamic type and dynamic value are nil
- many confusing error comparisons come from ordinary interface semantics, not from special error behavior
Use when
- debugging nil error surprises
- reviewing concrete error return types
- explaining the language layer under error handling style
Avoid
- returning a typed nil pointer as an
errorand expecting the interface value to be nil - treating
erroras a magical built-in exception channel - conflating interface assertions with error wrapping
Preferred pattern
if err != nil {
return fmt.Errorf("load config: %w", err)
}
Anti-pattern
- returning a
(*MyError)(nil)aserrorand expectingerr == nil
Explanation: This is tempting because the concrete pointer is nil, but once stored in an interface the dynamic type is still present.
Why
- many high-signal Go review questions about errors are really interface-semantic questions in disguise
Related pages
Sources
- The Go Programming Language Specification - Go Team
- Go Data Structures: Interfaces - Russ Cox
- Why is my nil error value not equal to nil? - Go Team