英文:
Go: How to check if a struct property was explicitly set to a zero value?
问题
以下是翻译好的内容:
type Animal struct {
Name string
LegCount int
}
snake := Animal{Name: "snake", LegCount: 0}
worm := Animal{Name: "worm"}
问题: 我如何在设置了snake
和worm
之后检查它们,以确定:
snake
的LegCount
是否被显式设置为0。worm
的LegCount
是否未被显式设置(因此基于其默认值)?
英文:
type Animal struct {
Name string
LegCount int
}
snake := Animal{Name: "snake", LegCount: 0}
worm := Animal{Name: "worm"}
Question: How can I check snake
and worm
after they've been set, to tell that:
snake
was explicitly set with aLegCount
of 0.- The
worm
'sLegCount
was not explicitly set (and therefore based off of its default value)?
答案1
得分: 12
这是翻译好的内容:
这是不可能区分的。
如果你正在从XML或JSON中解组数据,请使用指针。
type Animal struct {
Name *string
LegCount *int
}
对于不存在的字段,你将得到nil
值。
你可以在你的情况下使用相同的约定。
英文:
It is simply impossible to distinguish.
If you are unmarshalling data from XML or JSON, use pointers.
type Animal struct {
Name *string
LegCount *int
}
You will get nil
values for absent fields.
You can use the same convention in your case.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论