oop - Go 结构中的 omitempty 用例有哪些?

标签 oop go struct

我很好奇 omit empty 的用例是什么:

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

我读过 omitempty 可以防止在打印结构时显示空值,但我对此并不肯定。 另外,为什么要包含结构值的名称,即 Nameomitempty

最佳答案

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

根据关于编码 JSON 的部分:

Struct values encode as JSON objects. Each exported struct field becomes a member of the object, using the field name as the object key, unless the field is omitted.

The field of each string can be customized by the format string stored under the json key in the struct field's tag. The format string gives the name of the field, possibly followed by a comma separated list of options.

The "omitempty" option specifies that the field should be omitted from the encoding if the field has an empty value, defined as false, 0, a nil pointer, a nil interface value, and any empty array, slice, map, or string.

// 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:"-,"`

关于oop - Go 结构中的 omitempty 用例有哪些?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49043404/

相关文章:

c - 如何检查 switch 语句表达式中的结构数据值

arrays - 使用 struct 在 Go 中处理空 JSON 数组

C++ 接口(interface)错误;标识符 "class"未定义

go - 如何在包内调用未导出的函数?

oop - 减少构造函数的参数数量

go - 如何检查 slice 是否在 Go 中具有给定索引?

go - 附加到 slice 的多个实例

struct - 为什么编译器在结构成员未读时不发出警告?

c# - 当子类不使用抽象类中的函数时,是否有使用 NotImplementedException 的替代方法?

c++ - C++ 中的 OO 设计 - 用未知类型的子对象装饰父对象