Unmarshalling Embedded Structs in Go
This article addresses the issue of unmarshalling JSON data into a struct that contains an embedded struct. The provided example, in which the Inner struct is embedded in the Outer struct, demonstrates that the default UnmarshalJSON method for Inner is called and only the Data field is populated, leaving the Num field of Outer empty.
The reason for this behavior lies in Go's embedded struct mechanism. When an embedded struct is unmarshalled, the unmarshalling process directly targets the embedded struct and ignores the fields of the outer struct.
To address this, a simpler and more efficient solution is proposed: making the Inner struct an explicit field in the Outer struct.
By explicitly declaring Inner as a field, the UnmarshalJSON method of the Outer struct is called with the entire JSON data. Within this method, the Data field of Inner can be populated using the embedded Inner struct's UnmarshalJSON method, while the Num field can be populated separately. This approach ensures that both fields of the Outer struct are properly populated during unmarshalling.
Here's a working example to illustrate the solution:
<code class="go">type Outer struct { I Inner // Inner as explicit field Num int `json:"Num"` }</code>
The above is the detailed content of How to Unmarshal Embedded Structs in Go?. For more information, please follow other related articles on the PHP Chinese website!