Home >Backend Development >Golang >How to Distinguish Between Default and Explicitly Set Zero Values in Go Structs?
Default Struct Values in Go
In Go, primitive types such as int have default values. For int, this default value is 0. However, it can be difficult to distinguish between a manually set value of 0 and the default value.
Consider the following struct:
type test struct { testIntOne int testIntTwo int }
If we create a struct with one field set to 0, we cannot tell if the other field is set or still has its default value:
package main import "log" func main() { s := test{testIntOne: 0} log.Println(s) }
Solutions
Using a Pointer
One solution is to use a pointer for the field. Pointers have a zero value of nil, so we can check if the field is set:
type test struct { testIntOne *int testIntTwo *int } func main() { s := test{testIntOne: new(int)} log.Println(s.testIntOne != nil) // Output: true log.Println(s.testIntTwo != nil) // Output: false }
Using a Method
Another solution is to create a method that sets the field and tracks whether it has been set. The field itself should be unexported to prevent direct access:
type test struct { testIntOne int testIntTwo int oneSet, twoSet bool } func (t *test) SetOne(i int) { t.testIntOne, t.oneSet = i, true } func main() { s := test{} s.SetOne(0) log.Println(s.oneSet) // Output: true log.Println(s.twoSet) // Output: false }
The above is the detailed content of How to Distinguish Between Default and Explicitly Set Zero Values in Go Structs?. For more information, please follow other related articles on the PHP Chinese website!