Home > Backend Development > Golang > 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?

DDD
Release: 2024-12-04 17:20:15
Original
974 people have browsed it

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)
}
Copy after login

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
}
Copy after login
  • 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
}
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template