DevPath
Mid lesson · 12 min

Treat zero values and ownership deliberately

Know when an empty value is useful and when it hides missing data.

Read the zero value

Go initializes fields to zero values. That makes some types immediately useful, but zero can also be ambiguous: an amount of zero may be valid, while an omitted amount needs validation. A pointer or explicit presence field can distinguish missing from provided zero at an input boundary.

Avoid unintended sharing

Maps and slices can share underlying state when passed around. Decide whether a function is allowed to mutate its input. Copy when the caller expects independent output, and document intentional mutation. Be careful with a nil map: reading is safe, but assigning a key requires initialization.

var counts map[string]int
// counts["ok"] = 1 would panic.
counts = make(map[string]int)
counts["ok"] = 1

Test absence separately

Decode one payload with a missing field and another with the field explicitly set to zero. Assert that the handler follows the intended rule for each. Also test a copied slice after modifying the result; this reveals accidental storage sharing that value comparisons alone can miss.

Check your understanding

Why might an `int` field be insufficient for an optional JSON quantity?

Show explanation

Both omitted and explicitly provided zero decode to zero. Use a representation that records presence when that distinction matters.

Put this lesson into practice

A practice activity at this level in the same module.

Try: Depend on an interface, not a struct

Further reading

Primary references for this module. Check the current version when behavior or framework guidance may have changed.