1

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?

Elliot Reeve
  • 901
  • 4
  • 21
  • 39

1 Answers1

6

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}`
JimB
  • 104,193
  • 13
  • 262
  • 255
  • @Elliot Reeve You should also look this [answer](http://stackoverflow.com/questions/10998222/json-parsing-of-int64-in-go-null-values) – kingSlayer May 21 '15 at 17:36