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
Release: 2024-12-03 16:03:12
Original
232 people have browsed it

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

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

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

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

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template