LeYAUable
LeYAUable

Reputation: 1752

Are struct fields not mandatory?

I am learning Go, and came into something like:

type Something struct {
someField         String
}

That then is initialized as: Something{}

It was my understanding that we needed to initialize struct with the fields inside of it, but this is compiling and working, so can anybody explain me why this works?

Upvotes: 1

Views: 4239

Answers (1)

Nicholas Carey
Nicholas Carey

Reputation: 74307

Go does not have the notion of undefined. Every data type has a zero value.

Any variable/field/property that is not explicitly initialized is initialized by default with the zero value of its data types.

Whether or not that's a good thing is arguable[1], but it is the Go Way™.

[1] For instance, if I'm measuring voltage, a measurement of zero volts is different than not getting a voltage measurement at all. Or if I'm tabulating survey responses, no response is different than a response of "unknown"/"don't know"/"other".

Upvotes: 1

Related Questions