Home >Backend Development >Golang >How Can I Initialize Structs with Sensible Default Values in Go?
When working with structs in Go, initializing them with sensible default values can be crucial for ensuring their proper functioning. While Go lacks traditional constructors, there are several methods that can be employed to achieve this objective.
Init Method
The init method, although defined at the package level, can be utilized to perform initialization tasks for structs within the package. However, it isn't directly tied to the struct and is not invoked upon struct creation.
New Functions
A common practice in Go is to define New functions that return initialized pointers to structs. These functions allow for the assignment of default values during struct initialization:
func NewThing(someParameter string) *Thing { p := new(Thing) p.Name = someParameter p.Num = 33 // Sensible default value return p }
Condensed New Functions
For simple structs, a condensed version of the New function can be used, directly returning an initialized struct:
func NewThing(someParameter string) *Thing { return &Thing{someParameter, 33} }
Make Functions
Make functions are similar to New functions but return structs by value rather than pointers. This is useful when you don't require a pointer to the struct:
func makeThing(name string) Thing { return Thing{name, 33} }
Reference
For further information on allocation using new, refer to the effective Go documentation: https://go.dev/doc/effective_go#allocation
The above is the detailed content of How Can I Initialize Structs with Sensible Default Values in Go?. For more information, please follow other related articles on the PHP Chinese website!