Home > database >  Golang Unmarshalling behaviour: Excess fields?
Golang Unmarshalling behaviour: Excess fields?

Time:02-02

Suppose I have this struct:

type MyStruct struct {
    A string `json:"a"`
}

But I receive a response of the form:

{"a": "something", "b": "something", "c": "something"}

i.e. There are more fields than expected, but we only want the field A. Is it safe/allowed in golang to unmarshal the response into MyStruct?

CodePudding user response:

Yes, it is safe, and even used sometimes intentionally. If you need only a few fields from an input, you can define a structure that includes only those fields. In fact, it is harder to detect if there are fields in the input that are left unmarshaled.

  • Related