Pointers: The Map to Buried Treasure

Pointers: The Map to Buried Treasure in Go: A shipping clerk never carries a pallet to your desk so you can change its label.

The Analogy: The Warehouse Bay Number

A shipping clerk never carries a pallet to your desk so you can change its label. They look it up, write "bay 74" on a slip of paper and hand you the slip. You walk to bay 74 and re-label the pallet where it stands. The slip is tiny, you can photocopy it a hundred times, and every copy leads to the same pallet — because the slip is not the pallet, it is where the pallet is.

A Go pointer is that slip. It holds an address and nothing else, so it is the same small size regardless of what it points at: eight bytes on a 64 bit platform whether the target is a bool or a two-kilobyte struct. &x is "write down where x lives" and *p is "walk to that bay". Copying a pointer copies the slip, which is why two pointers can hand the same value to two different parts of a program, and why the previous lesson's copying rules stop applying the moment a pointer is involved.

That gives you the two reasons to reach for one. The first is mutation: a function that receives a copy of a struct can only scribble on the copy, but a function that receives the address can re-label the original. The second is cost: passing a large struct by value copies every byte at every call, while passing its address copies eight. Neither reason is "pointers are faster" in general — for a small struct the copy is often cheaper than the extra indirection — but both are concrete and easy to recognise.

The empty slip is nil, and walking to bay zero is a crash rather than a mystery: invalid memory address or nil pointer dereference is the single most common panic in Go programs. What Go removes is the other family of pointer bugs. There is no pointer arithmetic, so you cannot walk off the end of an array by accident. There are no dangling pointers, because the garbage collector keeps a pallet alive as long as any slip refers to it. And unlike C, returning the address of a local variable is completely correct — the compiler notices the address escaped and allocates the value where it will survive. A whole category of C bug simply does not exist here.


Syntax or Core Structure

Take an address, dereference it, watch value and pointer parameters diverge, and let the compiler insert the dereference for you.

package main

import "fmt"

type Counter struct{ N int }

func bumpValue(c Counter)    { c.N++ } // scribbles on a copy
func bumpPointer(c *Counter) { c.N++ } // walks to the original

func main() {
	x := 10
	p := &x
	fmt.Println("x:", x, "*p:", *p, "p == &x:", p == &x)

	*p = 20 // assign through the pointer
	fmt.Println("after *p = 20, x:", x)

	var np *int // the zero value of any pointer type
	fmt.Println("nil pointer:", np == nil)
	// fmt.Println(*np) // panic: invalid memory address or nil pointer dereference

	c := Counter{N: 1}
	bumpValue(c)
	fmt.Println("after bumpValue:", c.N)
	bumpPointer(&c)
	fmt.Println("after bumpPointer:", c.N)

	// Selectors dereference automatically: q.N means (*q).N.
	q := &c
	q.N += 5
	fmt.Println("after q.N += 5:", c.N, "same object:", q == &c)

	// new(T) allocates a zero T and returns its address.
	n := new(int)
	*n = 3
	fmt.Println("new(int):", *n)
}

Output:

x: 10 *p: 10 p == &x: true
after *p = 20, x: 20
nil pointer: true
after bumpValue: 1
after bumpPointer: 2
after q.N += 5: 7 same object: true
new(int): 3

bumpValue receives its own Counter and increments it; the caller's c never hears about it. bumpPointer receives eight bytes that say where the caller's c is, and c.N++ inside it is really (*c).N++. That automatic dereference on a selector is the one convenience Go grants: you write q.N for both a Counter and a *Counter, which is why so much Go code reads identically whether the variable is a value or a pointer.


Technical Depth: Addressability, nil, Escape and When to Bother

What a Go pointer can and cannot do

OperationAllowed
&x, *pYes
p == q, p != nilYes
p < q, p + 1, p++No. There is no pointer arithmetic and no ordering.
Convert *int to *float64No, not without unsafe (module 9).
Index a *[5]int as p[2]Yes. Pointer-to-array also works with len and range.
Index a *[]int as p[2]No. Slices get no such courtesy; write (*p)[2].
Print itTechnically yes, and never do it: the address is not reproducible between runs.

Addressability: what you may put & in front of

& requires an addressable operand — something that has a home you can point at.

ExpressionAddressableNote
&localVarYesSafe to return. The compiler heap-allocates if it escapes.
&s.FieldYesWhen s itself is addressable.
&arr[i], &slice[i]YesSlice elements live in the backing array.
&Point{1, 2}YesComposite literals are a deliberate exception.
&m["key"]NoMap elements are not addressable, which is why the maps lesson needed read-modify-write.
&f()NoA return value has no home. Assign it to a variable first.
&42, &"text"NoConstants are not addressable. Write a one-line helper that returns &v.
&str[0]NoStrings are immutable, so their bytes are not addressable.

nil, and what actually panics

On a nil *TResult
p == nilFine, and the check you should be writing.
*pPanic.
p.FieldPanic — it is a hidden dereference.
p.Method() with a pointer receiverRuns. The receiver is nil, and it panics only if the body touches a field.
p.Method() with a value receiverPanic. Calling it requires copying *p first.
Passing it to fmt.PrintlnFine, prints <nil>.

That fourth row is genuinely useful: a method with a pointer receiver that handles nil explicitly lets callers treat an absent value as an empty one, which is how (*Tree).Insert and much of net/http's optional plumbing are written. Module 5 covers receivers properly.

Escape analysis, in one paragraph

The compiler decides where each value lives. If a value's address never outlives the function, it goes on the stack and costs nothing to reclaim. If it escapes — returned, stored in a global, captured by a goroutine, or put into an interface — it is allocated on the heap and the garbage collector owns it. You never write malloc and you never write free, and return &Local{} is correct Go rather than the classic C bug. Inspect the decisions with go build -gcflags=-m; module 11 makes a lesson of it.

Pointer receivers and consistency

The rule of thumb: use a pointer receiver if the method mutates the receiver, if the struct is large, or if any method on the type already needs one. Mixing value and pointer receivers on the same type is how people end up with a mutation that silently targets a copy. Note also that only *T's method set includes pointer-receiver methods, which matters the moment interfaces appear.

Pointer to pointer

**T is legal and occasionally necessary: a function that has to replace the caller's pointer rather than modify what it points at needs the address of that pointer. Linked-list and tree insertion are the honest use cases, where **Node lets one loop handle "attach to the root" and "attach to a child" identically. Outside data structures it is almost always a sign that a return value would read better.

When a pointer is the wrong tool

TypeUse a pointer?
Slice, map, channel, functionNo. They already hold an internal reference. *[]T is only for replacing the slice header itself.
Interface valueNo. *io.Writer is nearly always a mistake; the interface is already a two-word handle.
Small struct you only readNo. Copying two ints beats an indirection and a possible heap allocation.
Struct with a mutex or other stateYes, always. Copying it breaks it.
Optional field in a config or JSON payloadYes. *bool distinguishes "false" from "not supplied".
Anything whose identity mattersYes. Two pointers compare equal only when they name the same object.

Real World Example: Layered Configuration with Optional Overrides

Every configuration system has the same problem: false and 0 are legitimate values, so a plain struct cannot say "this layer did not mention TLS". Pointer fields solve it, because nil is a value the caller cannot supply by accident.

package main

import (
	"fmt"
	"strings"
)

type Settings struct {
	Host    string
	Port    int
	TLS     bool
	Retries int
}

// A nil field means "this layer said nothing about it".
type Override struct {
	Host    *string
	Port    *int
	TLS     *bool
	Retries *int
}

// You cannot write &8080, so these tiny helpers exist. Each returns the
// address of its own parameter, which is a local variable -- perfectly
// safe in Go, because the compiler moves it to the heap for you.
func strPtr(v string) *string { return &v }
func intPtr(v int) *int       { return &v }
func boolPtr(v bool) *bool    { return &v }

// apply edits the caller's Settings in place, so it takes an address.
func apply(s *Settings, o Override) []string {
	var changed []string
	if o.Host != nil && *o.Host != s.Host {
		changed = append(changed, fmt.Sprintf("host %q -> %q", s.Host, *o.Host))
		s.Host = *o.Host
	}
	if o.Port != nil && *o.Port != s.Port {
		changed = append(changed, fmt.Sprintf("port %d -> %d", s.Port, *o.Port))
		s.Port = *o.Port
	}
	if o.TLS != nil && *o.TLS != s.TLS {
		changed = append(changed, fmt.Sprintf("tls %t -> %t", s.TLS, *o.TLS))
		s.TLS = *o.TLS
	}
	if o.Retries != nil && *o.Retries != s.Retries {
		changed = append(changed, fmt.Sprintf("retries %d -> %d", s.Retries, *o.Retries))
		s.Retries = *o.Retries
	}
	return changed
}

func main() {
	s := Settings{Host: "localhost", Port: 8080, TLS: false, Retries: 3}
	fmt.Printf("base:  %+v\n", s)

	layers := []struct {
		name string
		over Override
	}{
		{"env", Override{Host: strPtr("db.internal"), TLS: boolPtr(true)}},
		{"file", Override{}}, // config file absent: every field nil
		{"flags", Override{Port: intPtr(5432), Retries: intPtr(3)}},
		{"remote", Override{TLS: boolPtr(true), Retries: intPtr(5)}},
	}

	for _, l := range layers {
		changed := apply(&s, l.over)
		if len(changed) == 0 {
			fmt.Printf("%-7s no change\n", l.name)
			continue
		}
		fmt.Printf("%-7s %s\n", l.name, strings.Join(changed, ", "))
	}
	fmt.Printf("final: %+v\n", s)

	// A copy is immune, which is the whole point of taking the address.
	frozen := s
	apply(&frozen, Override{Port: intPtr(1)})
	fmt.Println("original port still", s.Port, "frozen port now", frozen.Port)
}

Output:

base:  {Host:localhost Port:8080 TLS:false Retries:3}
env     host "localhost" -> "db.internal", tls false -> true
file    no change
flags   port 8080 -> 5432
remote  retries 3 -> 5
final: {Host:db.internal Port:5432 TLS:true Retries:5}
original port still 5432 frozen port now 1

The pointer fields are not there for mutation — they are there to encode absence. Override{TLS: boolPtr(false)} means "this layer turns TLS off" and Override{} means "this layer had no opinion", and a plain bool field cannot tell those apart because both would arrive as false. The file layer prints no change for exactly that reason: all four fields are nil, so every guard short-circuits. This is the same reason encoding/json users reach for *bool and *int when they need to distinguish an absent key from a zero one.

apply takes *Settings because it edits the caller's value and returns only a description of what it did. The last three lines prove the contrast: frozen := s copies all four fields, and applying an override to &frozen leaves s.Port at 5432. That copy is genuinely independent only because Settings contains no pointers or slices; a struct holding a []string would hand the copy the same backing array, and "value semantics" would quietly stop at one level deep.

The three helper functions exist because &8080 does not compile — a constant has no address. Each one takes a parameter, which is a local variable, and returns its address. In C that would be a dangling pointer and a bug hunt; in Go the compiler sees the address escaping, allocates the value on the heap, and the garbage collector keeps it alive as long as the Override holds it. On Go 1.18 and later you can collapse all three into one generic func ptr[T any](v T) *T { return &v }, and many codebases have exactly that helper sitting in a internal/ptr package.

What the design costs is four != nil guards and a dereference on every read, and there is a real alternative worth knowing: a small wrapper struct like struct{ Value bool; Set bool }, which is the shape database/sql's NullBool uses. Wrappers cannot be nil, so they cannot panic, and they stay comparable so the enclosing struct keeps working with == and as a map key. Pointers win when a JSON or YAML decoder has to populate the type for you, because nil is what the decoder naturally leaves behind; wrappers win almost everywhere else.


Common Mistakes

  1. Dereferencing without checking. *p and p.Field on a nil pointer are the same panic. Any pointer that arrives from outside your function — a parameter, a map lookup result, a decoded payload — deserves a if p == nil before its first use.
  1. Taking the address of the loop variable in Go 1.21 or earlier. for _, v := range items { out = append(out, &v) } appended the same address every time, because v was one variable reused. Go 1.22 gives each iteration its own v and fixes it, but only when the module's go directive says 1.22 or later. Write &items[i] and the question never arises.
  1. Trying to take the address of a map element. &counts["a"] does not compile. Store pointers as the values (map[string]*Counter) if you need to mutate in place, or read-modify-write the whole value.
  1. Copying a struct that contains a mutex, and doing it through a pointer receiver you forgot to use. A single value receiver on a lock-bearing type copies the lock at every call. go vet catches most of it; consistency catches the rest.
  1. Believing pointers are always faster. An extra indirection defeats the cache, and taking an address can force a heap allocation the stack would have handled for free. For a struct of a few words, passing by value usually wins. Benchmark it (module 11) rather than guessing.
  1. Printing a pointer. fmt.Println(p) emits something like 0xc000012345, which changes between runs and makes tests and log diffs useless. Print *p, or compare pointers with == when identity is what you actually care about.
  1. Using *[]T or *map[K]V reflexively. Both already carry an internal reference, so a function taking []T can already modify the elements. The pointer is only needed to replace the slice header — for example a helper that appends and must have the caller see the new length.
  1. Returning a pointer to a slice element and then appending to the slice. The append may reallocate, leaving the pointer aimed at the old array. Anything written through it afterwards disappears. Take the pointer after all growth is finished, or store an index instead.
  1. Assuming a struct copy is deep. Copying a struct copies its pointer, slice and map fields as references. The two "independent" values share everything those fields point at.
  1. Keeping a pointer to one field of a huge struct. The garbage collector cannot free part of an object, so a single *int into a ten-megabyte struct keeps all ten megabytes alive. Copy the value out instead.
  1. Reaching for **T to avoid returning a value. Outside linked structures it reads badly and hides the data flow. Return the new pointer and let the caller assign it.

Best Practices

  • Pick one receiver style per type and never mix. If any method needs a pointer receiver, give them all pointer receivers; the consistency is worth more than the micro-optimisation.
  • Use &items[i] rather than &loopVar. It is correct on every Go version, it says what you mean, and it survives someone lowering the module's go directive.
  • Let nil mean "absent", and only that. A pointer field that can be nil for three different reasons is a bug factory. If you need more states, use a small wrapper struct or an explicit enum.
  • Check for nil at the boundary, not everywhere. Validate once when a pointer enters your package, then let the rest of the code assume it is good.
  • Prefer values for small immutable data and pointers for anything with identity or state. Configuration snapshots, coordinates and money are values; connections, buffers and caches are pointers.
  • Never print or persist an address. Use a stable identifier of your own if you need to correlate objects across log lines.
  • Write &T{...} instead of new(T). It allows field initialisation in the same expression and matches the rest of the language's literal syntax.
  • Run go build -gcflags=-m when allocation matters. It tells you which values escaped and why, which is more informative than any rule of thumb about pointers.

Practice Exercises

  1. Write func swap(a, b *int) that exchanges two values, and a second version func swapWrong(a, b int) that appears to. Call both on the same pair of variables and print the results, then explain in a comment which parameter list is copied and which is not.
  1. Build a map[string]*Counter where Counter has an N int field, increment one entry ten thousand times through the stored pointer, and confirm the total. Then rewrite it as map[string]Counter and describe precisely which line stops compiling and why.
  1. Take a slice of five structs. Store &items[0] in a variable, append enough elements to force the backing array to grow, then write through the saved pointer and print items[0]. Explain the result, and note that the exact number of appends needed is not something to assert in a test.
  1. Add an Optional variant to the configuration example: replace TLS *bool with TLS struct{ Value, Set bool } and adapt apply. Then compare the two designs on three axes — whether the type can panic, whether it stays comparable with ==, and how a JSON decoder would populate it.