new vs make
`new` allocates zeroed storage for any type; `make` initializes slices, maps, and channels into usable values.
Canonical guidance
- use
makefor slices, maps, and channels - use
newrarely, when a pointer to a zero value is specifically what you want - prefer composite literals when they read more clearly
Use when
- creating maps or channels
- deciding between pointer allocation styles
- explaining nil versus ready-to-use values
Avoid
new(map[string]int)new([]byte)when a literal ormakeis intended- treating
newandmakeas interchangeable
Preferred pattern
m := make(map[string]int)
Anti-pattern
- allocating with
newand then wondering why the map or channel is still unusable
Explanation: This is tempting because both forms allocate something, but they produce different kinds of results with different readiness semantics.
Why
- many early Go bugs are really about misunderstanding what was initialized
Related pages
Sources
- Effective Go - Go Team
- The Go Programming Language Specification - Go Team