Golang - 0 not as null



我将值传递给一个结构体,其中值具有omitempty

Offset uint64 'json:"offset,omitempty"'

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

我可以以某种方式将0声明为不定义为null的值吗?

用于序列化的结构通常使用指针来指示可空字段。它可以使处理结构变得有点麻烦,但具有区分nil0的优点

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

带有nil指针

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

在赋0值后

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