gpt4 book ai didi

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

转载 作者:数据小太阳 更新时间:2023-10-29 03:42:14 25 4
gpt4 key购买 nike

我很好奇 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com