Zero values
Design Go types so the zero value is useful when practical.
Canonical guidance
- prefer types whose zero value is ready for basic use
- make configuration additive instead of requiring a constructor for every case
- document when the zero value is not valid
Use when
- designing structs and APIs
- deciding whether a constructor is truly necessary
Avoid
- types that panic when zero-initialized unless unavoidable
- needless constructors that only assign zero values
Preferred pattern
var buf bytes.Buffer
buf.WriteString("ok")
Anti-pattern
type Client struct {
conn *Conn
}
- if zero
Clientis invalid, document it clearly or redesign the type
Explanation: This anti-pattern is tempting when constructors are familiar from other languages, but unnecessary ceremony fights Go’s zero-value conventions.
Why
- useful zero values reduce ceremony
- they fit Go’s allocation and declaration style naturally
Sources
- Effective Go - Go Team
- Go Code Review Comments - Go Team