Home >Backend Development >Golang >How Can I Initialize Go Structs Without Traditional Constructors?
Can Constructors Be Used to Initialize Go Structs?
In Go, structs can be initialized with sensible default values through various methods. Despite the lack of traditional constructors due to Go's non-OOP nature, there are alternative techniques to achieve similar functionality.
Method 1: NewThing Function with Pointer Return
When zero values are unsuitable, one option is to create a "NewThing" function that returns a pointer to a newly initialized struct:
type Thing struct { Name string Num int } func NewThing(someParameter string) *Thing { p := new(Thing) p.Name = someParameter p.Num = 33 // Set a sensible default value return p }
Method 2: Condensed "NewThing" Function
For simpler structs, a more concise method is available:
func NewThing(someParameter string) *Thing { return &Thing{someParameter, 33} }
Method 3: "makeThing" Function with Value Return
If returning a pointer is not desired, the function can be named "makeThing" and return a value:
func makeThing(name string) Thing { return Thing{name, 33} }
Reference
For further details, refer to the "Allocation with new" section in Effective Go.
The above is the detailed content of How Can I Initialize Go Structs Without Traditional Constructors?. For more information, please follow other related articles on the PHP Chinese website!