liveBook · Manning

Zero value

As explained in Go in Action, Second Edition

A zero value is the default value assigned to a newly declared Go variable when no explicit initial value is provided.

Go assigns every newly declared variable a default value when no explicit initializer is provided. Boolean values receive false, numeric values receive 0, strings receive "", and other types receive nil. This makes many variables immediately usable without a separate initialization step. section 2.4.8

The principle also applies when reading a missing map key: Go returns the zero value for the map's element type rather than panicking. Use the two-value lookup when distinguishing an absent key from a stored zero value matters. section 4.3.2

Membership queries with a map

A map[string]bool can store only members whose values are true. Looking up an unlisted name returns false, so a direct condition answers membership without requiring every nonmember to be stored. section 4.3.2

Missing numeric data

Reading wordsWritten["Eve"] from a map[string]int returns 0 when Eve has no entry, allowing an untracked person to be treated as having written zero words.

How Go in Action, Second Edition covers it

How deep it goes
Explains defaults and map behavior with runnable patterns, but defers other zero-value details to later treatment.
Examples
Demonstrates default integers, missing map entries, Boolean membership maps, and numeric word-count lookups.
What it assumes
Assumes familiarity with Go variables, types, declarations, and map key-value access.
What you can do after
Apply zero values in declarations and map lookups, and diagnose absent keys with two-value assignment.
How it connects
Connects variable declaration, type inference, maps, Boolean values, numeric values, and membership sets.

Also explained in

Compare how 5 books explain zero value →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.