'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?
Solution 1:[1]
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 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".
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | LeYAUable |
