Constructor Patterns
In this page:
A Basic Constructor Function
Since Go has no constructor keyword, the idiomatic pattern is a plain function, usually named NewType, that builds a struct value (often with some setup logic) and returns it.
Note: Naming the function NewX for a type X is the near-universal Go convention.
Example: A Basic Constructor Function
package main
import "fmt"
type Person struct {
Name string
Age int
}
func NewPerson(name string, age int) Person {
return Person{Name: name, Age: age}
}
func main() {
p := NewPerson("Divya", 27)
fmt.Println(p)
}
Login to try C/C++/Java/PHP code in the editor
Validating Input in a Constructor
A constructor function is a natural place to validate arguments and return an error if they're invalid, keeping bad data from ever forming a struct in the first place.
Example: Validating Input in a Constructor
package main
import (
"errors"
"fmt"
)
type Account struct {
Balance float64
}
func NewAccount(initial float64) (*Account, error) {
if initial < 0 {
return nil, errors.New("initial balance cannot be negative")
}
return &Account{Balance: initial}, nil
}
func main() {
acc, err := NewAccount(100)
fmt.Println(acc, err)
}
Login to try C/C++/Java/PHP code in the editor
Returning a Pointer from a Constructor
When a type has pointer-receiver methods, it's common for its constructor to return a *Type directly, so the value is immediately ready to be mutated through those methods without extra addressing.
Example: Returning a Pointer from a Constructor
package main
import "fmt"
type Counter struct {
value int
}
func NewCounter() *Counter {
return &Counter{value: 0}
}
func (c *Counter) Increment() {
c.value++
}
func main() {
c := NewCounter()
c.Increment()
c.Increment()
fmt.Println(c.value)
}
Login to try C/C++/Java/PHP code in the editor
- Expecting a special constructor syntax like other languages -- Go just uses ordinary functions, conventionally named NewXxx.
- Exporting all struct fields when a constructor is meant to enforce invariants, allowing callers to bypass validation by setting fields directly.
- Returning a struct value from a NewXxx function when a pointer was intended, causing inconsistency with the type's other pointer-receiver methods.
- Go has no dedicated constructor syntax -- a plain function conventionally named NewType builds and returns a value.
- Constructor functions can validate inputs and set sensible defaults before returning the struct.
- Returning a pointer (*Type) from a constructor is common when the type has pointer-receiver methods.
- Unexported fields combined with a constructor function enforce that objects are only created through valid initial states.
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: