~/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
- Pointers increase code complexity and errorproneness.
- 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.
- Less readable code and harder maintenance.
- Unintended side effects are more likely when passing pointers.
- Go has value semantics that are usually enough.
- Builtin types like slices, structs, and interfaces often avoid the need for explicit pointers.
Example, prefer not using pointers:
If you absolutely must mutate state shared across functions, use a pointer, but do so sparingly:
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.