7
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)?
Nathan Lippi
  • 4,967
  • 5
  • 25
  • 29
  • 2
    You can't with what you've shown. What is setting the values? Is it up to the programmer or via a package like json, database/sql? – JimB Mar 15 '16 at 14:40
  • 1
    @JimB: Thank you. I'm going to be processing data from an API. I'm assuming there's a way to do this with Unmarshal but I didn't want to make the scope of the question too large. – Nathan Lippi Mar 15 '16 at 14:42

1 Answers1

12

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.

Grzegorz Żur
  • 47,257
  • 14
  • 109
  • 105