A constructor creates and initializes a usable instance. Go has no language-level constructor mechanism, so packages commonly expose a New function that performs required setup and returns the instance. section 4.1.4 section 4.6
Listing 4.3 logger.go: Defining a new object
// Logger is used to log information.
type Logger struct {
threshold Level
}
// New returns you a logger, ready to log at the required threshold.
func New(threshold Level) *Logger {
return &Logger{
threshold: threshold, #1
}
}
A logger keeps its threshold unexported and requires callers to provide it through New, preserving encapsulation and consistent initialization. section 4.1.4
Use constructors when zero-value initialization is unsafe or when an instance requires parameters. A cache containing a map must initialize that map before use; exposing Cache while hiding its map encourages callers to use New. section 7.1.3
Listing 7.2 cache.go
The generic New function returns a Cache whose map is created with make, preventing operations on an uninitialized map. section 7.1.3
Constructor design choices include:
- Name the function New when the package context already identifies the type; avoid repetitive names such as pocketlog.NewPocketLog. section 4.1.4
- Return a pointer when callers benefit from sharing the constructed resource. section 4.1.4
- Use functional options for optional settings instead of accumulating excessive constructors. section 4.6












