xml.Marshal如果为空则忽略struct

I need to output an XML file, and I've constructed a few structs that represent it As a basic example, say this:

type Parent struct {
    XMLName xml.Name `xml:"parent"`
    Name    string   `xml:"name,omitempty"`
    Age     int64    `xml:"age,omitempty"`
    Child   Child    `xml:"child,omitempty`
}

type Child struct {
    XMLName  xml.Name `xml:"child,omitempty"`
    Name     string   `xml:"name,omitempty"`
    Gender   string   `xml:"gender,omitempty"`
    Thoughts string   `xml:",innerxml,omitempty"`
}

I expect that when I create a Parent without defining the child, and then marshal it into an XML file...

parent := Parent{
    Name: "Beatrice",
    Age: "23",
}
_ = xml.MarshalIndent(parent, "", "    ")

...that I should get an XML file not containing a child tag:

<parent>
    <name>Beatrice</name>
    <age>23</age>
</parent>

Instead, I get this:

<parent>
    <name>Beatrice</name>
    <age>23</age>
    <child></child>
</parent>

Why is the empty <child></child> tag there, and how can I get rid of it?

You have a few syntax errors but you can set child as a pointer:

type Parent struct {
    XMLName xml.Name `xml:"parent"`
    Name    string   `xml:"name,omitempty"`
    Age     int64    `xml:"age,omitempty"`
    Child   *Child    `xml:"child,omitempty"`
}

When it's nil, it will be empty.

Working Demo