liveBook · Manning

Missing value

As explained in Learn Go with Pocket-Sized Projects

nil is Go's predeclared zero-like value representing the absence of a valid reference, interface value, or other applicable value.

In Go, nil represents the absence of a usable value for applicable references and interfaces. Passing nil as an interface dependency can compile successfully but fail when the program calls through it. section 6.5.5

Use nil carefully in these situations:

  • A nil pointer or interface cannot provide the method or field the program tries to access; the runtime raises a panic for an invalid memory address or nil pointer dereference. section 6.5.5
  • Slices cannot be compared with == to other slices, but they can be compared with nil. section 5.1.2
  • Tests should replace a nil dependency with a small stub when the code under test calls its methods. section 6.5.5

A nil dependency panics

A conversion test passes nil to money.Convert as its exchange-rate provider: got, err := money.Convert(tc.amount, tc.to, nil). The call compiles, but invoking FetchExchangeRate produces a runtime panic. A stub implementing the interface supplies controlled rate and error values instead. section 6.5.5

got, err := money.Convert(tc.amount, tc.to, nil)

Inspect the minimal nil dependency passed to Convert, then compare it with the resulting runtime failure. section 6.5.5

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Explains nil through slice comparison, interface calls, runtime panic output, and replacement with a test stub.
Examples
Demonstrates nil in a money-conversion test and as the only comparable value for a slice.
What you can do after
Diagnose nil pointer dereferences and replace invalid nil test dependencies with interface-compatible stubs.
How it connects
Connects nil with pointers, interfaces, slices, method calls, panics, and test stubs.

Also explained in

Compare how 35 books explain missing value →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.