Default Values and Distinguishing Uninitialized Fields in Go
In Go, primitive types have default values. For instance, integers (int) are initialized to 0. However, when working with structs, distinguishing between a 0 value and an uninitialized field can be challenging.
For example, consider the code below:
package main import "log" type test struct { testIntOne int testIntTwo int } func main() { s := test{testIntOne: 0} log.Println(s) }
In this code, both testIntOne and testIntTwo are zero. However, testIntOne has been explicitly set to 0, while testIntTwo has been initialized by the default value. This ambiguity can lead to confusion in determining which fields have been explicitly set.
Is it possible to distinguish between these two cases?
No, Go does not track whether a field has been set or not. Therefore, it is impossible to know if a zero value is the result of initialization or an intentional assignment.
Workarounds
type test struct { testIntOne *int testIntTwo *int }
type test struct { testIntOne int testIntTwo bool // Tracks if testIntTwo has been set } func (t *test) SetTestIntTwo(val int) { t.testIntTwo = val t.isSetTestIntTwo = true } func main() { s := test{} s.SetTestIntTwo(0) fmt.Println(s.isSetTestIntTwo) // Output: true }
The above is the detailed content of How Can I Differentiate Between Default and Explicitly Set Zero Values in Go Structs?. For more information, please follow other related articles on the PHP Chinese website!