Home >Backend Development >Golang >How Do I Initialize Structs in Go Without Constructors?
Constructors in Go
When dealing with custom types defined as structs in Go, it may be desirable to initialize them with sensible default values upon creation. However, unlike traditional object-oriented programming languages, Go does not have dedicated constructors for structs.
Alternative to Constructors: New Functions
To address this situation, Go engineers commonly employ "New" functions. These functions accept necessary parameters for initialization and return a pointer to a new struct instance:
type Thing struct { Name string Num int } func NewThing(someParameter string) *Thing { p := new(Thing) p.Name = someParameter p.Num = 33 return p }
This approach allows for the initialization of struct values with specific defaults, such as assigning a value to the "Num" field.
Condensed New Function Syntax
For simple structs, a condensed syntax can be used:
func NewThing(someParameter string) *Thing { return &Thing{someParameter, 33} }
Non-Pointer Return Types
If returning a pointer is not desired, a "make" function can be used instead of "New":
func makeThing(name string) Thing { return Thing{name, 33} }
The above is the detailed content of How Do I Initialize Structs in Go Without Constructors?. For more information, please follow other related articles on the PHP Chinese website!