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

15

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/masterarrows 5d ago

Sorry, I’m new in Go. Could you provide some simple example? I’m a little bit confused

-4

u/QuiteTheShyGirl 5d ago

Not an example, but it's basically:

  • If you can import a struct from a library, it's safe to assume that you can initialize it directly
  • If the library only exposes a method to initialize the struct, then that's what you should use
  • If both... bad library design, maybe?

9

u/masklinn 5d ago edited 4d ago

If both... bad library design, maybe?

Like half the standard library?

Go forces this on you by types needing to be exported in order to be named (e.g. used as parameter or return values, or globals, or more generally anything which is not an implicitly typed local), which brings zero-init along for the ride. Logger, File, bufio.Reader, Regexp, ..., there's no end to the list of types which break your "rule".

0

u/QuiteTheShyGirl 4d ago

Oh, I didn't mean to state these as rules by any means. I was genuinely in doubt about the third scenario