问题
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:
snake
was explicitly set with aLegCount
of 0.- The
worm
'sLegCount
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