转到:如何检查struct属性是否显式设置为零值? [英] Go: How to check if a struct property was explicitly set to a zero value?
本文介绍了转到:如何检查struct属性是否显式设置为零值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
type Animal struct {
Name string
LegCount int
}
snake := Animal{Name: "snake", LegCount: 0}
worm := Animal{Name: "worm"}
问题:设置后,如何检查 snake
和 worm
,以告知:
Question: How can I check snake
and worm
after they've been set, to tell that:
-
snake
已明确设置为LegCount
为0. - 没有明确设置
worm
的LegCount
(因此基于其默认值)?
snake
was explicitly set with aLegCount
of 0.- The
worm
'sLegCount
was not explicitly set (and therefore based off of its default value)?
推荐答案
根本无法区分.
如果要从XML或JSON解组数据,请使用指针.
If you are unmarshalling data from XML or JSON, use pointers.
type Animal struct {
Name *string
LegCount *int
}
对于缺少的字段,您将获得 nil
值.
You will get nil
values for absent fields.
在您的情况下,您可以使用相同的约定.
You can use the same convention in your case.
这篇关于转到:如何检查struct属性是否显式设置为零值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文