liveBook · Manning

Constructor method

As explained in Learn Go with Pocket-Sized Projects

A constructor is a mechanism or operation that creates and initializes an instance of a type.

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
// New creates a usable Cache.
func New[K comparable, V any]() Cache[K, V] {
    return Cache[K, V]{
        data: make(map[K]V),
    }
}

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

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains zero values, required parameters, map setup, naming, pointer returns, and functional options, but not language-level constructor syntax.
Examples
Demonstrates New for a generic cache with an initialized map and for a logger requiring a logging threshold.
What it assumes
Assumes familiarity with Go structs, zero values, exported fields, pointers, maps, and package-qualified function calls.
What you can do after
Build it from scratch using a package-level New function that validates or applies required initialization before returning an instance.
How it connects
Connects constructors with zero values, encapsulation, pointers, generics, functional options, and public APIs.

Also explained in

Compare how 13 books explain constructor method →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.