Skip to main content
Module 5 · Lesson 5 of 525/50 in the course~10 min
Module lessons (5/5)

Constructor Pattern `New...`

Lesson preview5 hands-on exercises readyCourse Go · Module 5 — Structs and methods

Go has no constructors: the convention is a NewT(...) *T function that does validation and returns errors.

What you'll learn in this lesson

  • Write factory functions NewT(...) *T and NewT(...) (*T, error) according to the Go convention.
  • Respect the rule of returning nil to the pointer in case of validation failure.
  • Apply the advanced functional options pattern (type Option func(*Server)) for useful extensible and zero-value configurations.

Overview

Go does not have the constructor(...) nor new T(...) syntax typical of classic OOP. To encapsulate default values or mandatory validations, a factory function called New<Type> is defined.

If the package exposes only one main type (such as bytes.Reader), by convention the factory is simply called New(...); otherwise NewUser, NewStore, NewClient:

Sections covered in this lesson

  1. 1Base factory and validating factory (*T, error)
  2. 2Multiple Constructors and Functional Options
  3. 3Factory multiple and zero-value already usable
  4. 4Guided practice
  5. 5Check for understanding
Pro Lesson · Module 5 — Structs and methods

Unlock "Constructor Pattern `New...`" and the full Course Go curriculum

Go has no constructors: the convention is a `NewT(...) *T` function that does validation and returns errors.

Unlock all 5 hands-on exercises in this lesson plus every advanced WebAssembly module with automated checks.

  • Instant access to all advanced modules in Course Go plus 17 more courses
  • Hands-on browser exercises with automated test suites and solutions
  • 14-day money-back guarantee processed via Paddle.com

14-day guarantee · Cancel anytimeModule 1, all 18 interactive games, and cheatsheets are always free.