go - 使用指针时,omitempty 在编码/xml 中不起作用?

标签 go

我正在使用返回 XML 的 REST API 并尝试解码 XML,但我遇到的问题似乎是 omitempty不管用。这是一个工作 XML 文件的示例:

<?xml version='1.0' encoding='UTF-8'?>
<customer uri="/api/customers/339/" id="339">
    <name>
        <first>Firstname</first>
        <last>Lastname</last>
    </name>
    <email>myemail@example.com</email>
    <billing>
        <address>
            <address1>123 Main St.</address123>
            <address2></address2>
            <city>Nowhere</city>
            <state>IA</state>
            <country>USA</country>
            <zip>12345</zip>
        </address>
    </billing>
</customer>

这是一个“坏”记录的例子

<?xml version='1.0' encoding='UTF-8'?>
<customer uri="/api/customers/6848/" id="6848">
    <name>
        <first>Firstname</first>
        <last>Lastname</last>
    </name>
    <email/>
    <billing/>
</customer>

现在我的结构设置如下:

 type Customer struct {
     ID      int      `xml:"id,attr"`
     Name    *Name    `xml:"name,omitempty"`
     Billing *Billing `xml:"billing,omitempty"`
 }

 type Billing struct {
     Address *Address `xml:"address,omitempty"`
 }

 type Address struct {
     address_1 string `xml:",omitempty"`
     address_2 string `xml:",omitempty"`
     city      string `xml:",omitempty"`
     postal    string `xml:",omitempty"`
     country   string `xml:",omitempty"`
 }

 type Name struct {
     first, last string
 }

当 XML 遵循第一个示例的模式时,通读所有有效的记录 <billing></billing>但是当它达到类似 <billing/> 的记录时它抛出以下错误:panic: runtime error: invalid memory address or nil pointer dereference

谁能帮我弄清楚发生了什么以及如何解决它?

最佳答案

您可能误解了 ,omitempty 是什么方法。它仅在编码 数据时生效。如果你解码 <billing/>使用 ,omitempty 到指针字段上,它仍然会初始化该字段。然后,由于 XML 元素为空,Billing 的字段本身不会被设置。实际上,如果您假设 customer.Billing != nil表示 customer.Billing.Address != nil ,你会得到观察到的 panic 。

备注:http://play.golang.org/p/dClkfOVLXh

关于go - 使用指针时,omitempty 在编码/xml 中不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18394911/

相关文章:

go - 对 proto 文件使用共享的外部包?

go - 在 Go 中找到两个整数之间的最小值的正确方法是什么?

python - 带有 Web 后端的日志存储

go - 使用 Go 从 html 中解析列表项

file - 在 Golang 中写入响应后,HTTP 请求被中止

json - 如何在 JSON 中编码和解码 big.Int?

GoLang 二叉树 - 使用接口(interface)和结构

go - 为什么Go中的位运算符比除法和模运算慢?

json - 在 go 中解析 JSON

go - 用指针或值嵌入 Go