Nathan Lippi
Nathan Lippi

Reputation: 5237

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

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)?

Upvotes: 7

Views: 680

Answers (1)

Grzegorz Żur
Grzegorz Żur

Reputation: 49201

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.

Upvotes: 12

Related Questions