Home > Backend Development > Golang > How Can I Distinguish Between Default and Explicitly Set Zero Values in Go Structs?

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

DDD
Release: 2024-12-04 09:36:11
Original
614 people have browsed it

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

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

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

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!

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