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 }
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3