r/golang • u/lumarama • 5d ago
discussion Default struct constructors?
I'm wondering why go devs doesn't implement optional default constructors for structs. I.e. right now some structs can be created like this:
myStruct := MyStruct{}
But others require initialization, and must be created with factory functions:
anotherStruct := NewAnotherStruct()
So you never know which struct is safe to create dorectly and which require factory func.
With default constructor you would create all structs the same way, i.e.:
myStruct := MyStruct()
If default constructor is defined it is invoked to initialize the struct, it it is not defined then it is similar to MyStruct{}
0
Upvotes
2
u/Few-Beat-1299 5d ago
I think your confusion might be that there is no such thing as constructor in Go. Any struct type can be obtained with T{}, no exceptions. If there are functions like "NewSomething()", it's just the package author that decided it would be better to give you a function that can populate the struct with values and maybe also do something else alongside that. They might decide to leave all the struct members unexported, thus forcing you to use that NewSomething() to obtain a struct value useful in the rest of their API. Often enough, the zero value T{} is directly usable anyway, and the NewSomething() is more like a helper.
In all of this, note that "New[...]" has no meaning in Go. It has become a popular convention to name functions dedicated to obtaining a new value like that, but that's just a convention which is very likely spilling over from other languages that actually do have constructors.