how to distinguish between missing attributes and attributes with default values?
Use pointers!
Imagine the following:
type Person struct { Name *string Age int }
then try to unmarshal this: { "Age": 30 }
{ "Age": 30 }
You will get this:
fmt.Printf("%#v\n", p) > main.Person{Name:(*string)(nil), Age:30}
if a key is missing, it's a simple nil check away.
Another nice technique I like to use is as follows:
Declare an ok interface:
ok
type ok interface { OK() error }
Implement it on your type:
func (p *Person) OK() error { if p.Name == nil { return errors.New("missing field: name") } return nil }
Then simply:
p.OK() > 2009/11/10 23:00:00 missing field: name
You can see the full example in the go playground:
play.golang.org/p/P_88niVqOke
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Use pointers!
Imagine the following:
then try to unmarshal this:
{ "Age": 30 }
You will get this:
if a key is missing, it's a simple nil check away.
Another nice technique I like to use is as follows:
Declare an
ok
interface:Implement it on your type:
Then simply:
You can see the full example in the go playground:
play.golang.org/p/P_88niVqOke