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?
CodePudding user response:
Go does not have the notion of undefined. Every data type has a zero value.
- https://dave.cheney.net/2013/01/19/what-is-the-zero-value-and-why-is-it-useful
- https://go.dev/tour/basics/12
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".
CodePudding user response:
Elements/fields are optional as said by @icza.
If not provided they will have the zero value applicable for the type of the element/field. For instance, in a int
the "zero value" would be 0
.
Many thanks to @icza and @Sergio Tulentsev for the comments that basically are the answer.