Are struct fields not mandatory?

Issue

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?

Solution

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 its 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".

Answered By – Nicholas Carey

Answer Checked By – Robin (GoLangFix Admin)

Leave a Reply

Your email address will not be published.