A zero value is the default value a Go variable receives without an explicit initializer. Prefer types whose zero values are immediately usable when that avoids setup, boilerplate, and missed initialization. section 8.10 section 5.6
Use value fields for ready-to-use test output
A test environment can store strings.Builder values rather than *strings.Builder pointers. A declared testEnv then has usable builders immediately; their addresses can be assigned where an io.Writer is required. Pointer fields instead begin nil and panic until explicitly initialized. section 5.4.2 section 5.4.1
Listing 5.5 Test environment (hit/cmd/hit_test.go)
package main
import "strings"
type testEnv struct {
stdout strings.Builder
stderr strings.Builder
}
The value fields let a zero-valued testEnv collect stdout and stderr without constructor-style setup. section 5.4.2
A useful zero value does not mean every operation is safe without work. Shortener can be declared and used directly, but its Shorten method must initialize its nil map before inserting an entry. Reading from that nil map remains safe. When making a zero value useful adds complexity, use a constructor instead. section 8.2.3
Check zero-value designs for these trade-offs:
- Treat an integer option carefully when zero is both its zero value and a meaningful choice. For example, MaxRetries set to 0 can be indistinguishable from an unset option when defaults are applied. section 6.4.2
- Avoid unintentionally copying stateful values such as strings.Builder or sync.Mutex. Use pointer receiver methods where needed to prevent copying a mutex. section 5.4.1
- Choose a constructor when forcing a type to support immediate zero-value use would add undue complexity. section 8.2.3
A service that initializes itself on first write
A Shortener holds a map of keys to links. Its zero value has a nil map, so Shorten checks for nil and allocates the map before storing a link. Callers can therefore declare var links Shortener and call Shorten without first calling NewShortener. section 8.2.3




