Go: How to check if a struct property was explicitly set to a zero value?

荒凉一梦 提交于 2020-12-08 07:03:54

问题


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:


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.



来源:https://stackoverflow.com/questions/36014343/go-how-to-check-if-a-struct-property-was-explicitly-set-to-a-zero-value

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!