Home > Backend Development > Golang > How to Unmarshal Embedded Structs in Go?

How to Unmarshal Embedded Structs in Go?

Mary-Kate Olsen
Release: 2024-11-04 12:13:30
Original
869 people have browsed it

How to Unmarshal Embedded Structs in Go?

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>
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template