Zero values and absence

suggest change

Every Go variable starts with a zero value: 0, "", false, nil or a struct of zero values. There is no "undefined" and no uninitialized memory.

The price is that the zero value means two things: "the value is zero" and "there is no value". For many programs that's fine. For others the difference matters: a volume set to 0 is not the same as a volume not set at all, an empty name in a JSON PATCH request is not the same as a missing name, and a NULL column in a database is not the same as 0.

This article shows how to design types whose zero value is useful, and the idiomatic ways to represent absence when zero isn't enough: the comma-ok idiom, (value, bool) and (value, error) returns, pointers, a generic optional type, JSON and SQL nullability, and the nil interface trap.

The problem

A struct can't tell you which fields were set:

package main

import "fmt"

type Settings struct {
	Volume  int // 0..100, default 50
	Retries int // default 3
}

func main() {
	var notSet Settings
	setToZero := Settings{Volume: 0}

	fmt.Printf("%+v\n", notSet)
	fmt.Printf("%+v\n", setToZero)
	fmt.Println(notSet == setToZero)
}
{Volume:0 Retries:0}
{Volume:0 Retries:0}
true

Both values are identical, so any code that receives a Settings can't know whether the caller wanted silence or didn't care. If 0 is a valid value and you also need a default, you must represent absence explicitly.

Before reaching for that, ask whether you can avoid the problem by making the zero value meaningful.

Make the zero value useful

A Go proverb says: make the zero value useful. Many standard library types work without a constructor:

You can design your own types the same way. Lazily allocate what the zero value can't hold:

package main

import (
	"bytes"
	"fmt"
	"strings"
	"sync"
)

type Counter struct {
	mu     sync.Mutex
	counts map[string]int
}

func (c *Counter) Inc(key string) {
	c.mu.Lock()
	defer c.mu.Unlock()
	if c.counts == nil {
		c.counts = make(map[string]int) // lazy init
	}
	c.counts[key]++
}

func (c *Counter) Get(key string) int {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.counts[key] // reading a nil map is fine
}

func main() {
	var buf bytes.Buffer // ready to use
	buf.WriteString("hello ")
	fmt.Fprintf(&buf, "%d", 42)
	fmt.Println(buf.String())

	var sb strings.Builder
	sb.WriteString("built")
	fmt.Println(sb.String())

	var c Counter // no constructor needed
	fmt.Println(c.Get("a"))
	c.Inc("a")
	c.Inc("a")
	fmt.Println(c.Get("a"))

	var s []int // nil slice: len 0, append works
	s = append(s, 1, 2)
	fmt.Println(s, len(s))
}
hello 42
built
0
2
[1 2] 2

The same idea applies to settings: choose names so that zero is the sensible default. Instead of Enabled bool defaulting to true, use Disabled bool, which defaults to false. Instead of a Timeout where 0 means "use 30 seconds", document that 0 means "no timeout", as http.Client.Timeout does.

When zero must mean "not set" and also be a valid value, use one of the techniques below.

The comma-ok idiom

Several Go operations return a second, boolean value that reports whether the first one is real:

operation form ok is false when
map lookup v, ok := m[key] key is not in the map
type assertion v, ok := x.(T) dynamic type of x is not T
channel receive v, ok := <-ch channel is closed and drained
os.LookupEnv v, ok := os.LookupEnv(name) variable is not set

Without ok you get the zero value, indistinguishable from a stored zero:

package main

import (
	"fmt"
	"os"
)

func main() {
	stock := map[string]int{"apples": 5, "pears": 0}

	fmt.Println(stock["pears"], stock["plums"]) // both 0

	for _, name := range []string{"apples", "pears", "plums"} {
		n, ok := stock[name]
		fmt.Printf("%-6s n=%d ok=%v\n", name, n, ok)
	}

	// type assertion
	var v any = 0
	if n, ok := v.(int); ok {
		fmt.Println("int:", n)
	}
	s, ok := v.(string)
	fmt.Printf("string: %q ok=%v\n", s, ok)

	// channel receive
	ch := make(chan int, 1)
	ch <- 0
	close(ch)
	x, ok := <-ch
	fmt.Println("recv:", x, ok)
	x, ok = <-ch
	fmt.Println("recv:", x, ok)

	// environment variables
	os.Setenv("EMPTY_VAR", "")
	val, ok := os.LookupEnv("EMPTY_VAR")
	fmt.Printf("EMPTY_VAR=%q ok=%v\n", val, ok)
	val, ok = os.LookupEnv("NO_SUCH_VAR")
	fmt.Printf("NO_SUCH_VAR=%q ok=%v\n", val, ok)
}
0 0
apples n=5 ok=true
pears  n=0 ok=true
plums  n=0 ok=false
int: 0
string: "" ok=false
recv: 0 true
recv: 0 false
EMPTY_VAR="" ok=true
NO_SUCH_VAR="" ok=false

Use the one-value form only when the zero value is a fine answer, like counting with m[key]++. See Get value by key and Zero value of a map for more about maps, and Environment variables for os.Getenv vs. os.LookupEnv.

Returning (value, bool) or (value, error)

Your own functions should follow the same convention. Return a boolean when "not found" is an ordinary outcome, and an error when the caller probably needs to report it:

package main

import (
	"errors"
	"fmt"
	"slices"
)

type User struct {
	ID   int
	Name string
}

var users = []User{{1, "alice"}, {2, "bob"}}

// FindUser reports whether a user with the given id exists.
func FindUser(id int) (User, bool) {
	i := slices.IndexFunc(users, func(u User) bool { return u.ID == id })
	if i < 0 {
		return User{}, false
	}
	return users[i], true
}

var ErrNotFound = errors.New("not found")

// LoadUser returns an error wrapping ErrNotFound if the user doesn't exist.
func LoadUser(id int) (User, error) {
	if u, ok := FindUser(id); ok {
		return u, nil
	}
	return User{}, fmt.Errorf("user %d: %w", id, ErrNotFound)
}

func main() {
	if u, ok := FindUser(2); ok {
		fmt.Println("found:", u.Name)
	}
	if _, ok := FindUser(3); !ok {
		fmt.Println("user 3 doesn't exist")
	}

	_, err := LoadUser(3)
	fmt.Println(err)
	fmt.Println(errors.Is(err, ErrNotFound))
}
found: bob
user 3 doesn't exist
user 3: not found
true

Conventions:

This works well for function results. For struct fields and parameters, where there is no second return value, you need to store the "is set" information next to the value.

Pointers as optional values

The traditional Go way to make a field optional is a pointer: nil means "not set", a non-nil pointer points to the value, which can be zero:

package main

import "fmt"

type Settings struct {
	Volume  *int
	Retries *int
}

func apply(s Settings) {
	volume, retries := 50, 3 // defaults
	if s.Volume != nil {
		volume = *s.Volume
	}
	if s.Retries != nil {
		retries = *s.Retries
	}
	fmt.Println("volume:", volume, "retries:", retries)
}

func main() {
	apply(Settings{})

	// Go 1.26+: new accepts an expression
	apply(Settings{Volume: new(0), Retries: new(10)})

	// before Go 1.26 you needed a variable (or a helper function)
	zero := 0
	apply(Settings{Volume: &zero})
}
volume: 50 retries: 3
volume: 0 retries: 10
volume: 0 retries: 3

Before Go 1.26 there was no way to take the address of a literal, so code was littered with temporary variables or helpers like func ptr[T any](v T) *T { return &v }. Since Go 1.26 the built-in new accepts an expression: new(0), new("text") and new(time.Now()) allocate a variable initialized to that value and return a pointer to it.

Pointers are idiomatic and work with encoding/json, but they have costs:

package main

import "fmt"

type Config struct {
	Port *int
}

func main() {
	port := 8080
	a := Config{Port: &port}
	b := a // copies the pointer, not the int

	*b.Port = 9090
	fmt.Println(*a.Port, *b.Port)

	var c Config
	defer func() { fmt.Println("recovered:", recover()) }()
	fmt.Println(*c.Port) // nil dereference
}
9090 9090
recovered: runtime error: invalid memory address or nil pointer dereference

Use pointers for optional fields when you need JSON or library compatibility. For values that live inside your program, a value-based optional type is safer.

A generic optional type

With generics you can write an optional type that stores the value and a flag inline. There is no nil to dereference, no aliasing and no allocation:

package main

import "fmt"

// Opt holds a value of type T or nothing.
// The zero value is an empty Opt.
type Opt[T any] struct {
	v  T
	ok bool
}

func Some[T any](v T) Opt[T] { return Opt[T]{v: v, ok: true} }

func None[T any]() Opt[T] { return Opt[T]{} }

func (o Opt[T]) Get() (T, bool) { return o.v, o.ok }

func (o Opt[T]) IsSet() bool { return o.ok }

func (o Opt[T]) Or(def T) T {
	if o.ok {
		return o.v
	}
	return def
}

func (o Opt[T]) String() string {
	if !o.ok {
		return "None"
	}
	return fmt.Sprintf("Some(%v)", o.v)
}

type Settings struct {
	Volume  Opt[int]
	Retries Opt[int]
	Name    Opt[string]
}

func main() {
	s := Settings{Volume: Some(0)}
	fmt.Println(s.Volume, s.Retries, s.Name)

	fmt.Println("volume:", s.Volume.Or(50))
	fmt.Println("retries:", s.Retries.Or(3))

	if name, ok := s.Name.Get(); ok {
		fmt.Println("name:", name)
	} else {
		fmt.Println("no name")
	}

	// Opt[T] is comparable when T is comparable
	fmt.Println(s.Retries == None[int](), s.Volume == Some(0))
}
Some(0) None None
volume: 0
retries: 3
no name
true true

Design notes:

The standard library has no general optional type, but database/sql has one for SQL (see below). Don't overuse Opt: a (T, bool) return or a well-chosen zero default is usually simpler.

nil vs. empty slices and maps

A nil slice and an empty slice behave the same for len, range and append, but they are different values. Most code shouldn't care, but some does, notably encoding/json:

package main

import (
	"encoding/json"
	"fmt"
)

type Resp struct {
	Tags []string `json:"tags"`
}

func main() {
	var nilSlice []string
	emptySlice := []string{}

	fmt.Println(len(nilSlice), len(emptySlice))
	fmt.Println(nilSlice == nil, emptySlice == nil)

	a, _ := json.Marshal(Resp{Tags: nilSlice})
	b, _ := json.Marshal(Resp{Tags: emptySlice})
	fmt.Println(string(a), string(b))

	var m map[string]int
	c, _ := json.Marshal(m)
	fmt.Println(string(c))
}
0 0
true false
{"tags":null} {"tags":[]}
null

A JSON API client often expects [] for an empty list, and null may break it. Initialize slices you return in API responses (Tags: []string{} or make([]string, 0)), or normalize them before encoding. Don't check s == nil to mean "empty": use len(s) == 0, which is true for both. See Zero value of slice.

JSON: omitting zero values

When encoding, encoding/json has two options for leaving fields out:

omitempty never omits structs, which is surprising with time.Time:

package main

import (
	"encoding/json"
	"fmt"
	"time"
)

type Size struct {
	W, H int
}

type Item struct {
	Count   int       `json:"count,omitempty"`
	Price   *float64  `json:"price,omitempty"`
	Tags    []string  `json:"tags,omitempty"`
	Created time.Time `json:"created,omitempty"`
	Updated time.Time `json:"updated,omitzero"`
	Size    Size      `json:"size,omitzero"`
}

func main() {
	b, _ := json.Marshal(Item{})
	fmt.Println(string(b))

	b, _ = json.Marshal(Item{Count: 0, Price: new(0.0), Tags: []string{}})
	fmt.Println(string(b))
}
{"created":"0001-01-01T00:00:00Z"}
{"price":0,"created":"0001-01-01T00:00:00Z"}

Notice that:

Prefer omitzero in new code. See Configuring JSON serialization for other struct tag options.

JSON: absent vs. null vs. zero

When decoding, there are three cases for a field: the key is missing, the key is null, or the key has a value. A plain int field is 0 in all three cases if the value is 0. A pointer field distinguishes "has a value" from the other two:

package main

import (
	"encoding/json"
	"fmt"
)

type Patch struct {
	Name  *string `json:"name"`
	Age   *int    `json:"age"`
	Email *string `json:"email"`
}

func show[T any](field string, p *T) {
	if p == nil {
		fmt.Printf("  %s: absent or null\n", field)
	} else {
		fmt.Printf("  %s: %#v\n", field, *p)
	}
}

func main() {
	inputs := []string{
		`{"name": "", "age": 0}`,
		`{"email": null}`,
	}
	for _, s := range inputs {
		var p Patch
		if err := json.Unmarshal([]byte(s), &p); err != nil {
			panic(err)
		}
		fmt.Println(s)
		show("name", p.Name)
		show("age", p.Age)
		show("email", p.Email)
	}
}
{"name": "", "age": 0}
  name: ""
  age: 0
  email: absent or null
{"email": null}
  name: absent or null
  age: absent or null
  email: absent or null

That's enough for most requests. For HTTP PATCH semantics, where a missing key means "leave unchanged" and null means "clear this field", you need all three states. encoding/json calls UnmarshalJSON only for keys present in the input (including null values, for non-pointer types), so a custom type can record presence:

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
)

// Field records whether a JSON key was present and whether it was null.
type Field[T any] struct {
	Present bool // key appeared in the JSON
	Null    bool // value was null
	Value   T
}

func (f *Field[T]) UnmarshalJSON(data []byte) error {
	f.Present = true
	if bytes.Equal(data, []byte("null")) {
		f.Null = true
		return nil
	}
	return json.Unmarshal(data, &f.Value)
}

func (f Field[T]) String() string {
	switch {
	case !f.Present:
		return "absent"
	case f.Null:
		return "null"
	default:
		return fmt.Sprintf("%#v", f.Value)
	}
}

type UserPatch struct {
	Name  Field[string] `json:"name"`
	Age   Field[int]    `json:"age"`
	Email Field[string] `json:"email"`
}

func main() {
	in := `{"name": "", "email": null}`
	var p UserPatch
	if err := json.Unmarshal([]byte(in), &p); err != nil {
		panic(err)
	}
	fmt.Println("name: ", p.Name)
	fmt.Println("age:  ", p.Age)
	fmt.Println("email:", p.Email)

	// applying the patch to a stored value
	email := "old@example.com"
	if p.Email.Present {
		if p.Email.Null {
			email = "" // clear the field
		} else {
			email = p.Email.Value
		}
	}
	fmt.Printf("email after patch: %q\n", email)
}
name:  ""
age:   absent
email: null
email after patch: ""

To encode Field as well you would add a MarshalJSON method and an IsZero method so that omitzero skips absent fields. See Custom JSON marshaling.

SQL: NULL columns

Scanning a NULL column into a string or int64 fails with an error, because there is no zero value that means NULL. database/sql provides nullable wrapper types: sql.NullString, sql.NullInt64, sql.NullBool, sql.NullTime and others, plus the generic sql.Null[T] (Go 1.22+). Each has the value and a Valid flag:

package main

import (
	"database/sql"
	"fmt"
)

func main() {
	// rows.Scan calls Scan for each column
	var name sql.Null[string]
	name.Scan(nil)
	fmt.Printf("%+v\n", name)
	name.Scan("alice")
	fmt.Printf("%+v\n", name)

	var age sql.NullInt64
	age.Scan(int64(0))
	fmt.Printf("%+v\n", age)

	// database/sql calls Value for query arguments
	v, _ := sql.Null[string]{}.Value()
	fmt.Printf("%v\n", v)
	v, _ = sql.Null[int64]{V: 0, Valid: true}.Value()
	fmt.Printf("%v\n", v)
}
{V: Valid:false}
{V:alice Valid:true}
{Int64:0 Valid:true}
<nil>
0

rows.Scan calls the Scan method of these types for each column and database/sql calls Value when they are used as query arguments, so sql.Null[T]{} is written as NULL and sql.Null[int64]{V: 0, Valid: true} as 0. In real code you use them like this:

var email sql.Null[string]
err := db.QueryRow("SELECT email FROM users WHERE id = ?", id).Scan(&email)
if err != nil {
	return err
}
if email.Valid {
	fmt.Println("email:", email.V)
}

A pointer (*string) also works as a scan destination: it is set to nil for NULL. If you don't need to distinguish NULL from the zero value, convert in SQL with COALESCE(email, '') and scan into a plain string. See Querying.

Command-line flags: set vs. default

The flag package fills variables with their default values, so after parsing you can't tell whether -workers=4 was passed or 4 is the default. FlagSet.Visit calls a function only for flags that were set on the command line (VisitAll visits all of them):

package main

import (
	"flag"
	"fmt"
)

func main() {
	fs := flag.NewFlagSet("app", flag.ExitOnError)
	workers := fs.Int("workers", 4, "number of workers")
	verbose := fs.Bool("verbose", false, "verbose output")
	fs.Parse([]string{"-workers=4"})

	set := map[string]bool{}
	fs.Visit(func(f *flag.Flag) { set[f.Name] = true }) // only flags that were set

	fmt.Println("workers:", *workers, "explicitly set:", set["workers"])
	fmt.Println("verbose:", *verbose, "explicitly set:", set["verbose"])
}
workers: 4 explicitly set: true
verbose: false explicitly set: false

The nil interface trap

An interface value is nil only when both its dynamic type and its value are unset. An interface holding a nil pointer is not nil. This most often bites with errors:

package main

import (
	"errors"
	"fmt"
)

type MyError struct{ Msg string }

func (e *MyError) Error() string { return e.Msg }

func validate(n int) error {
	var err *MyError // nil pointer
	if n < 0 {
		err = &MyError{"negative"}
	}
	return err // BUG: never a nil interface
}

func validateFixed(n int) error {
	if n < 0 {
		return &MyError{"negative"}
	}
	return nil
}

func main() {
	err := validate(5)
	fmt.Println(err == nil)
	fmt.Printf("%T %v\n", err, err)

	err = validateFixed(5)
	fmt.Println(err == nil)

	var me *MyError
	err = validate(-1)
	fmt.Println(errors.As(err, &me), me.Msg)
}
false
*main.MyError <nil>
true
true negative

validate returns a *MyError that happens to be nil, wrapped in a non-nil error interface, so err == nil is false and callers think validation failed. The fix is to return the literal nil for "no error" and never declare result variables of a concrete error type. See Custom error types.

The same applies to any interface: absence is represented by a nil interface, not by an interface containing a nil pointer.

Checking for the zero value and supplying defaults

A few helpers make working with zero values easier:

package main

import (
	"cmp"
	"fmt"
	"os"
	"reflect"
	"time"
)

func IsZero[T comparable](v T) bool {
	var zero T
	return v == zero
}

type Point struct{ X, Y int }

func main() {
	fmt.Println(IsZero(0), IsZero(""), IsZero(Point{}), IsZero(Point{1, 0}))

	// reflect works for non-comparable types too
	var s []int
	fmt.Println(reflect.ValueOf(s).IsZero(), reflect.ValueOf([]int{}).IsZero())

	// cmp.Or returns the first non-zero argument
	host := cmp.Or(os.Getenv("APP_HOST"), "localhost")
	port := cmp.Or(0, 8080)
	fmt.Println(host, port)

	// time.Time has its own IsZero
	var t time.Time
	fmt.Println(t.IsZero(), t)
	fmt.Println(t == time.Time{})
}
true true true false
true false
localhost 8080
true 0001-01-01 00:00:00 +0000 UTC
true

cmp.Or treats zero as "not set", so it can't express "use 0 even though the default is 8080". When you need that, go back to the comma-ok idiom, a pointer or Opt.

Choosing a representation

situation use
zero can be a sensible default plain value, document the meaning of zero
function may not find a result (T, bool)
"not found" should be reported (T, error) with a sentinel error
optional field in JSON or library structs pointer, omitzero
optional field inside your program Opt[T] value type
distinguish missing, null and value in JSON custom type with UnmarshalJSON
nullable database column sql.Null[T] or a pointer
defaults from several sources cmp.Or

Summary

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents