Default Struct Values
In Go, default values are assigned to fields of a struct that are not initialized during struct declaration. For primitive types like int, this default value is 0. However, determining whether this value has been explicitly set or is the default value can be problematic.
Is There a Difference?
Unfortunately, Go does not track whether a field has been set or not. Therefore, there is no way to distinguish between a field that has been initialized to 0 and a field that has not been set at all.
Workarounds
1. Using Pointers:
By using pointers, you can take advantage of their nil zero value. If a pointer is nil, it indicates that it has not been set.
type test struct { testIntOne *int testIntTwo *int } func main() { s := test{testIntOne: new(int)} fmt.Println("testIntOne set:", s.testIntOne != nil) fmt.Println("testIntTwo set:", s.testIntTwo != nil) }
2. Using Methods:
You can also define a method to set a field and track whether it has been set.
type test struct { testIntOne int testIntTwo int oneSet, twoSet bool } func (t *test) SetOne(i int) { t.testIntOne, t.oneSet = i, true } func (t *test) SetTwo(i int) { t.testIntTwo, t.twoSet = i, true } func main() { s := test{} s.SetOne(0) fmt.Println("testIntOne set:", s.oneSet) fmt.Println("testIntTwo set:", s.twoSet) }
The above is the detailed content of How Can I Distinguish Between Default and Explicitly Set Zero Values in Go Structs?. For more information, please follow other related articles on the PHP Chinese website!