Skip to content
Tutorials Center
My learning

Topics

Lesson 45 of 147 ยท Structs and Methods

Constructors, Options and Builders

Learn how Go creates objects - NewX functions, validating invariants, the functional options pattern, config structs, builders and making the zero value useful.

Go has no constructors in the language. There is no new Thing(...) syntax that runs special code, and no rule that a type must be created in a particular way. You can always write Thing{} and get a valid value in memory. What Go has instead is a convention: a plain function, usually named NewThing, that builds a value, checks that it makes sense and returns it.

This lesson covers the whole toolbox for creating values well. You will see when you don't need a constructor at all (the zero value is useful), how to write NewX functions that protect invariants and return errors, and three ways of handling many optional settings: config structs, functional options (the most common idiom in Go libraries) and builders. It builds on Structs, Methods and Value vs Pointer Receivers.

Make the zero value useful

Before writing any constructor, ask whether you need one. Every Go type has a zero value, and the best designs make that value work. A famous example is sync.Mutex: you declare var mu sync.Mutex and use it, with no NewMutex call. bytes.Buffer and strings.Builder behave the same way.

Here a Tally type works straight from its zero value, even though it contains a map:

Go A useful zero value

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Two details make this work. Reading from a nil map is safe and returns the zero value, and only writing needs the map to exist, so Add creates it on first use. When a type can be designed like this, users get a simpler API and fewer bugs. Reach for a constructor only when the zero value can't be valid.

The NewX convention

When a value needs setup, such as allocating a map, setting defaults or checking arguments, write a function whose name starts with New. If the package has one main type, the function is just New, as in errors.New or bufio.NewReader:

Go A simple constructor

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Go has no rule about returning a value or a pointer from NewX. Return a pointer when the type has pointer receivers, contains a mutex or is large; return a value for small immutable types such as time.Time. Because the fields here are lowercase, code in other packages can't set them directly, so the constructor is the only way to build a Rectangle with real data. That is how you enforce invariants.

Validating invariants and returning errors

A constructor is the right place to reject bad input. If construction can fail, return (T, error):

Go A constructor that validates

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Every Email that came out of NewEmail is guaranteed to be trimmed and lowercased. That guarantee only holds if outside code can't write Email{address: "junk"}, and within another package it can't, because the field is unexported. (Inside the same package it can, so keep construction discipline there too.) A typical panicking variant, named MustX, exists for values that are known at compile time, such as regexp.MustCompile.

A zero value Email{} still exists and is invalid. Document what the zero value means, or make methods handle it. Constructors reduce invalid states, but Go can't eliminate them.

Too many parameters: config structs

A constructor with eight positional parameters, half of them optional, is hard to read and impossible to extend without breaking callers. The simplest cure is a config struct passed by value. Zero fields mean "use the default":

Go A config struct with defaults

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Callers name only what they care about, and new fields can be added later without breaking anyone, since unnamed fields keep their zero value. The standard library's http.Server is built this way. The weakness appears when "zero" is a legitimate setting: with this design you can't ask for MaxConns: 0 or turn a boolean default-true setting off. Pointer fields or the next pattern solve that.

Functional options

The functional options pattern is Go's most popular answer to optional settings. Each option is a function that modifies the object being built, and the constructor takes a variadic list of them:

Go The functional options pattern

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

What makes this pattern good:

  • The call site reads like a sentence: NewClient(url, WithTimeout(2*time.Second)).
  • Required values stay positional (baseURL), optional ones become options.
  • Setting an option to zero is distinguishable from not setting it.
  • You can add options in later versions without changing NewClient's signature.
  • Options can be stored, combined and reused, for example var testOpts = []Option{WithTimeout(time.Second)}.

The cost is some boilerplate: one small function per setting, and no compile-time hint listing available options except through documentation and autocomplete on the With prefix.

Options that can fail

When an option's value can be invalid, let options return an error and have the constructor stop at the first failure:

Go Options that return errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

You will see this shape in many libraries. Because PoolOption is a named function type, you can also give it methods or declare an interface, but a plain function type is usually all you need.

The builder pattern

A builder collects settings through chained method calls and produces the final value in a last Build step. It is common when you also want to validate everything at once or construct an immutable result:

Go A builder with chained methods

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The builder remembers the first error and reports it in Build, so the chain doesn't need an if err != nil after every step. The standard library does the same with bufio.Scanner and sql.Rows: methods keep going, and one final call returns the error. Use builders for step-by-step construction of complex values; for plain optional settings, functional options are usually lighter.

Choosing a style

Situation Best choice
Zero value can be valid No constructor at all
A few required values Plain NewX(a, b)
Many fields, zero means default Config struct
Zero is a real setting, API will grow Functional options
Step-by-step, validated assembly Builder

Whichever you choose, keep constructors small and boring. Return concrete types, not interfaces, so callers see every method (a Go proverb: accept interfaces, return structs), and name the function after what it returns.

If your type has an Options struct or functional options, put the defaults in the constructor body, in one place, so documentation can say exactly what they are.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What makes the zero value of sync.Mutex a good design?

    Types whose zero value is ready to use need no constructor, which keeps APIs small and hard to misuse.
  2. 2. In the functional options pattern, what is an Option?

    An Option is typically func(*T). The constructor loops over the variadic options and calls each one on the new value.
  3. 3. Why can NewClient(url, WithRetries(0)) set retries to 0 when a config struct often cannot?

    With a config struct, zero means both "unset" and "zero". An option runs only if the caller passes it, so a deliberate zero is preserved.
  4. 4. What is a good reason for a builder to store an error field and return it from Build?

    Chained methods return the builder so calls can follow each other. Remembering the first error and returning it once at the end avoids breaking the chain.
  5. 5. What does the Go proverb "accept interfaces, return structs" suggest for a constructor?

    Returning a concrete type keeps the API flexible: callers can still assign it to any interface they need.

Summary

  • Go has no constructor syntax; a NewX function is the convention for building values.
  • Prefer designs where the zero value is useful, and create maps or slices lazily when needed.
  • Constructors validate input and can return (T, error); unexported fields make the constructor the only way in from other packages.
  • Config structs give named, extensible settings but can't distinguish "unset" from zero.
  • Functional options (func(*T)) are readable, extensible and let zero be a real value.
  • Builders suit step-by-step construction and can defer errors to Build.
  • Return concrete types from constructors.

Next: Struct Tags