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

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-03 16:03:12226browse

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!

Statement:
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