Explicit Zero in JSON Without Extra Variables: How new(0) in Go 1.26 Simplifies omitempty FieldsBrief · digest for December 2
Brief≈ 1 min

Explicit Zero in JSON Without Extra Variables: How new(0) in Go 1.26 Simplifies omitempty Fields

In PATCH requests, you often need to tell "field omitted" apart from "set to 0." Put omitempty on a plain int and encoding/json silently drops zero from the JSON—leaving your server unable to tell whether a limit was skipped or reset to zero.

That is why optional fields use a *int pointer: nil omits the key, while a pointer to 0 keeps it. Previously, Go wouldn't let you write &0, forcing you to declare v := 0 or a ptr(0) helper. In Go 1.26, the built-in new function now accepts a value or expression directly.

type Patch struct {
    // nil omits the key, while a pointer to 0 preserves it
    Limit *int `json:"limit,omitempty"`
}

a, _ := json.Marshal(Patch{})
b, _ := json.Marshal(Patch{Limit: new(0)})
// a -> {}
// b -> {"limit":0}

Calling new(0) allocates a variable, initializes it to zero, and returns *int. new(false), new(""), and expressions like new(yearsSince(born)) work just as cleanly for JSON and Protocol Buffers, while new(int) still works as before.

Two quick caveats: you need go 1.26 in go.mod, and an untyped 0 defaults to int—for *int64, cast explicitly with new(int64(0)).

Want a deep diveVotes help us choose what to break down in detail. This material has 0 votes.
Sources · 2