~/When To Use Pointers In Go

Oct 15, 2022


Only use pointers in Go when you actually need them. Passing by reference can be accomplished without pointers in many cases. If you only need to avoid copying large values, pass by reference with a pointer, but do it only if profiling or performance testing shows problems.

Advantages of avoiding pointers

  1. Pointers increase code complexity and errorproneness.
  2. Nil pointer dereference panics are a common bug: if a pointer is nil and you access it, you get a runtime error that crashes your program.
  3. Less readable code and harder maintenance.
  4. Unintended side effects are more likely when passing pointers.
  5. Go has value semantics that are usually enough.
  6. Builtin types like slices, structs, and interfaces often avoid the need for explicit pointers.

Example, prefer not using pointers:

1
2
3
4
5
6
7
8
9
type Data struct {
    Value int
}

// Pass by value, safer in most cases
func Increment(d Data) Data {
    d.Value++
    return d
}

If you absolutely must mutate state shared across functions, use a pointer, but do so sparingly:

1
2
3
4
5
func IncrementPointer(d *Data) {
    if d != nil {
        d.Value++
    }
}

If you are unsure, just use values, not pointers. Converting to a pointer type later is simple. Most of the time, copying values is fast enough.

Further reading and rationale can be found at the Google Go Style Decisions Guide and this Go playground example.

Tags: [go] [pointers] [programming]