Module lessons (5/5)
Constructor Pattern `New...`
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(...) *TandNewT(...) (*T, error)according to the Go convention. - Respect the rule of returning
nilto 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
- 1Base factory and validating factory
(*T, error) - 2Multiple Constructors and Functional Options
- 3Factory multiple and zero-value already usable
- 4Guided practice
- 5Check for understanding
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.