"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How Can I Differentiate Between Default and Explicitly Set Zero Values in Go Structs?

How Can I Differentiate Between Default and Explicitly Set Zero Values in Go Structs?

Posted on 2025-03-12
Browse:253

How Can I Differentiate Between Default and Explicitly Set Zero Values in Go Structs?

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

  • Use Pointers: Pointers have a nil zero value, so you can check if a pointer has been set by examining whether it is nil.
type test struct {
    testIntOne *int
    testIntTwo *int
}
  • Create a Setter Method: You can create a method to set the value of a field and track whether it has been set.
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
}
Latest tutorial More>

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