liveBook · Manning

Reference

As explained in 100 Go Mistakes and How to Avoid Them

A pointer is a Go value that holds the memory address of another value or represents the absence of such an address.

A pointer holds an address; a nil pointer holds no address. That distinction matters when a value such as 0 is valid but an omitted value needs different treatment. In a configuration struct, an int field cannot distinguish an explicitly supplied port of 0 from an omitted port: both are 0. A *int can distinguish them, though callers must create a variable to take its address. section 2.11.1

Pointing at the wrong customer

Suppose a range loop stores &customer in a map for each customer in a slice. In the demonstrated loop, every entry ends up pointing at the last customer's data because the loop variable has the same address on each iteration. Taking &customers[i] instead stores pointers to the slice elements. Creating a separate current := customer inside the loop instead gives each entry a pointer to its own copy. section 4.3

Check what a pointer keeps shared—or reachable:

  • A shortened slice can retain pointer-bearing elements in its backing array. Copy the wanted elements if the old capacity is unnecessary; otherwise, clear the unwanted references so their backing arrays can be collected. section 3.10.2
  • A value receiver copies its struct. If that struct contains a sync.Mutex, the copy does not protect a shared critical section. Use a pointer receiver, or store a *sync.Mutex and initialize it; a nil mutex pointer will panic when locked. go vet can flag a lock passed by value. section 9.14
  • Scanning SQL NULL into a string fails. Scan into a *string to obtain nil for NULL, or use sql.NullString when an explicit validity field better communicates the intent. section 10.4.4

How 100 Go Mistakes and How to Avoid Them covers it

How deep it goes
Works through observable pointer mistakes and contextual fixes rather than pointer arithmetic or memory layout.
Examples
Shows map entries all referencing one customer and a copied mutex producing a data race.
What it assumes
Assumes familiarity with Go structs, slices, methods, and goroutines; explains nil through concrete configuration and mutex cases.
What you can do after
Diagnose/debug with it: choose the intended slice element address and prevent mutex copies across calls.
How it connects
Connects pointers to slice backing arrays, garbage collection, and nullable SQL columns.

Also explained in

Compare how 17 books explain reference →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Go Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.