gpt4 book ai didi

go - 默认结构值

转载 作者:数据小太阳 更新时间:2023-10-29 03:41:38 25 4
gpt4 key购买 nike

在 Go 中,我知道类型有默认值。在本例中采用初始化为 0 的 int。

我有一个问题,对我来说 int 中的 0 可以是一个有效值,所以我需要检查它是否由我设置或初始化。有什么办法可以完全分辨它们之间的区别吗?

考虑到 following code ...我需要能够分辨 testIntOnetestIntTwo 之间的区别,但它们看起来是一样的!

package main

import "log"

type test struct {
testIntOne int
testIntTwo int
}

func main() {
s := test{testIntOne: 0}

log.Println(s)
}

最佳答案

您无法区分,它不会跟踪字段(或变量)是否已设置。

使用指针

您可以使用具有nil 的指针zero value ,所以如果没有设置,你可以知道:

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)
}

输出(在 Go Playground 上尝试):

testIntOne set: true
testIntTwo set: false

当然 new() 只能用于获取指向 int 值为 0 的指针。有关更多选项,请参阅此问题:How do I do a literal *int64 in Go?

使用方法

您还可以使用一种方法来设置字段,该方法可以额外跟踪“isSet”属性。在这种情况下,您必须始终使用提供的方法来设置字段。最好是不导出字段,这样其他人(在您的包之外)将无法直接访问它们。

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)
}

输出(在 Go Playground 上尝试):

testIntOne set: true
testIntTwo set: false

关于go - 默认结构值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57621976/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com