Go结构中omitempty的用例是什么?

问题描述 投票:-2回答:1

我很好奇用例如何省略以下内容:

type Example struct {
    ID           string  `json:",omitempty"`
    Name         string  `json:"name,omitempty"`
    exchangeRate float64 `json:"string"`
}

我已经读过omitempty防止在打印结构时出现空值,但我对此并不乐观。另外,为什么要包括结构值的名称,即Nameomitempty

oop go struct
1个回答
0
投票

感谢Cerise Limon建议在godoc.org上查看godocs。

根据编组JSON的部分:

结构值编码为JSON对象。除非省略该字段,否则每个导出的struct字段都将成为该对象的成员,使用字段名称作为对象键。

每个字符串的字段可以通过存储在struct字段标记中的json键下的格式字符串进行自定义。格式字符串给出了字段的名称,可能后跟逗号分隔的选项列表。

“omitempty”选项指定如果字段具有空值(定义为false,0,nil指针,nil接口值以及任何空数组,切片,映射或字符串),则应从编码中省略该字段。

// Field appears in JSON as key "myName".
Field int `json:"myName"`

// Field appears in JSON as key "myName" and
// the field is omitted from the object if its value is empty,
// as defined above.
Field int `json:"myName,omitempty"`

// Field appears in JSON as key "Field" (the default), but
// the field is skipped if empty.
// Note the leading comma.
Field int `json:",omitempty"`

// Field is ignored by this package.
Field int `json:"-"`

// Field appears in JSON as key "-".
Field int `json:"-,"`
© www.soinside.com 2019 - 2024. All rights reserved.