如何检查一个结构体属性是否被显式设置为零值?

huangapple go评论79阅读模式
英文:

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

问题: 我如何在设置了snakeworm之后检查它们,以确定:

  1. snakeLegCount是否被显式设置为0。
  2. wormLegCount是否未被显式设置(因此基于其默认值)?
英文:
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:

  1. snake was explicitly set with a LegCount of 0.
  2. The worm's LegCount 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.

huangapple
  • 本文由 发表于 2016年3月15日 22:38:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/36014343.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定