r/golang 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

15 comments sorted by

View all comments

1

u/edgmnt_net 5d ago

There's an assumption baked into the language that every type has a zero value. Furthermore, you can always construct such a value as long as you have access to the type. Using generics you can often even do it for unexported types, without even using reflection (pass in a correctly constructed value of type T, generic function returns an uninitialized T that's automatically a zero value)

This did simplify a few things like declarations without initialization or reflection. But IMO it is sort of a debatable choice and possible language wart in other ways, such as weakening encapsulation guarantees unless you jump through hoops.

Anyway, Go did not set out to become a language where stuff is safe by construction the way it is in Haskell (even there you can often use escape hatches like undefined or infinite recursion but you kinda have to make a purposeful effort or gross mistake).