Golang – 0 不等于 null

huangapple go评论96阅读模式
英文:

Golang - 0 not as null

问题

我正在将值传递给一个具有omitempty的结构体中的字段。

Offset uint64 'json:"offset,omitempty"'

然而,当我将0作为offset的值传递时,它也被省略了。

我是否可以以某种方式声明0作为一个不被定义为null的值?

英文:

I am passing values to a struct in which the value has omitempty

Offset uint64 'json:"offset,omitempty"'

However when I pass 0 as the value of offset it is also omitted.

Can I somehow declare 0 as a value which is not defined as null?

答案1

得分: 6

序列化结构通常使用指针来表示可为空的字段。这样做会使得与结构一起工作稍微麻烦一些,但它有一个优点,就是可以区分nil0

type T struct {
    Offset *uint64 `json:"offset,omitempty"`
}

使用空指针:

t := T{}
// 序列化为 "{}"

在分配零值之后:

t.Offset = new(uint64)
// 序列化为 `{"offset":0}`
英文:

Structures for serialization often use pointer to indicate a nullable field. It can make working with the structure a little more cumbersome to work with, but has the advantage of discerning between nil and 0

type T struct {
	Offset *uint64 `json:"offset,omitempty"`
}

With a nil pointer

t := T{}
// marshals to "{}"

And after allocating a zero value

t.Offset = new(uint64)
// marshals to `{"offset":0}`

huangapple
  • 本文由 发表于 2015年5月21日 23:18:16
  • 转载请务必保留本文链接:https://go.coder-hub.com/30377861.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定