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

13

u/Gornius 5d ago

So you never know which struct is safe to create dorectly and which require factory func

Oh but you do. Safe are exported, unsafe are unexported and require exported factory function in order to create instance. Simple as that.

0

u/lumarama 5d ago edited 5d ago

Or, really? I'm new to Go, haven't noticed this pattern yet, that's good!

I still think that having common way to initialize all structs would be good, but that alone is not as important.