~/Using Constructors in Golang

Feb 19, 2021


Go does not support constructors in the traditional OOP sense. Instead, idiomatic Go uses regular functions for initializing structs. A typical constructor is a function named NewTypeName.

Example:

1
2
3
4
5
6
7
8
type User struct {
    Name string
    Age  int
}

func NewUser(name string, age int) *User {
    return &User{Name: name, Age: age}
}

This pattern is preferred for setting default values or performing validation before returning a pointer to a struct.

You do not need to use constructors, but they are useful for abstraction, safety, and clarity. See the official Go FAQ for more information.

Tags: [golang]