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

type Animal struct {
    Name string
    LegCount int
}

snake := Animal{Name: "snake", LegCount: 0}
worm := Animal{Name: "worm"}

Q: How can I check snakeand wormafter they were set to announce that:

  • snakewas explicitly set using LegCount0.
  • worm LegCount has not been explicitly installed (and therefore based on its default value)?
+4
source share
1 answer

It is simply impossible to distinguish.

If you detached data from XML or JSON, use pointers.

type Animal struct {
    Name *string
    LegCount *int
}

You will get the values nilfor the missing fields.

You can use the same convention in your case.

+9
source

All Articles