Understand Go Pointers (& and *) Without Guessing
Learn how &x and *p work in Go, why value parameters copy data, and how to guard against nil pointer dereferences. After this, pointer bugs stop being guesswork.
Skip ahead
Already know & and * syntax? Jump to Case 2: distinguishing omitted vs. empty fields in JSON PATCH updates or Case 4: when pointers actually hurt performance.
Every function call in Go passes arguments by value (a copy). When a helper tries to double an int or update a struct field and the caller's variable stays unchanged, pass-by-value is why. Pointers (& and *) solve two concrete problems in everyday Go: letting a function mutate the caller's variable in place, and representing "missing / not provided" cleanly as nil. Verified on Go 1.27.
Case 1: Address-of (&), dereference (*), and nil safety
Read the two operators as opposites: &n takes the memory address of n (producing type *int), and *x dereferences that pointer to read or write the value stored there:
package main
import "fmt"
func doubleVal(x int) { x *= 2 }
func doublePtr(x *int) {
if x != nil {
*x *= 2
}
}
func main() {
n := 10
doubleVal(n)
fmt.Println("after doubleVal:", n)
doublePtr(&n)
fmt.Println("after doublePtr:", n)
var p *int
doublePtr(p)
fmt.Println("nil ptr safe:", p == nil)
}
after doubleVal: 10
after doublePtr: 20
nil ptr safe: true
Without if x != nil, dereferencing an uninitialized var p *int crashes immediately with runtime error: invalid memory address or nil pointer dereference.
Case 2: Real API use case—JSON PATCH with optional *string
Suppose your API supports PATCH /users/7 where clients send only the fields they want to update. With a plain Name string field, both {} (don't touch the user's name) and {"name":""} (explicitly clear the name) decode to ""—making it impossible to tell them apart! Using Name *string solves it cleanly:
package main
import (
"encoding/json"
"fmt"
)
type PatchUser struct {
Name *string `json:"name"`
}
func main() {
for _, raw := range []string{`{}`, `{"name":""}`, `{"name":"Ana"}`} {
var p PatchUser
_ = json.Unmarshal([]byte(raw), &p)
if p.Name == nil {
fmt.Printf("%s -> omitted (keep existing)\n", raw)
} else {
fmt.Printf("%s -> set to %q\n", raw, *p.Name)
}
}
}
{} -> omitted (keep existing)
{"name":""} -> set to ""
{"name":"Ana"} -> set to "Ana"
Case 3: Returning a pointer to a local variable is completely safe in Go
Developers coming from C worry that returning &localVar from a constructor creates a dangling pointer. In Go, the compiler's escape analysis automatically allocates localVar on the heap whenever its address outlives the function:
func NewUser(name string) *User {
u := User{Name: name}
return &u // safe: Go moves u to the heap automatically
}
Case 4: When to pass values vs. pointers (and why pointers aren't always faster)
| Type / Case | Use value (T) |
Use pointer (*T) |
|---|---|---|
Small scalars & structs (int, bool, time.Time) |
Yes—fast stack copy, never nil |
Only to mutate caller's value or mark "unset" |
Structs containing sync.Mutex |
Never—copying a lock breaks synchronization | Always pass *T |
| Slices, maps, channels | Yes—headers already reference backing storage | Only if replacing the slice header itself |
Avoid wrapping tiny structs in pointers "for speed" without benchmarking: copying a 32-byte struct on the stack is nearly free, whereas taking pointers often forces heap allocations and extra garbage-collector work.
💡 Tip
Go forbids pointer arithmetic (p++ does not compile), eliminating C-style buffer-overflow pointer bugs while keeping explicit mutation crystal clear.
Common mistakes
- Passing
*[]Tjust to modify elements: A slice value already shares its backing array sos[0] = 99mutates the caller's elements; return the updated slice when callingappend. - Dereferencing optional JSON pointers without checking
!= nil: One missing field causes a nil-pointer panic in production. - Passing a struct containing a
sync.Mutexby value: Copies the lock state; rungo vet ./...to catch this automatically.
⚠ Warning
A nil-pointer dereference panics the current goroutine—and outside an HTTP handler with recovery middleware, crashes the entire Go process immediately. Always guard optional pointers with if p != nil.
What happens if you skip this
Guessing between T and *T leads to functions that silently mutate local copies, PATCH endpoints that wipe omitted fields, and production crashes from unchecked nil pointers.
Related course: Go for Beginners.
About
Learn how &x and *p work in Go, why value parameters copy data, and how to guard against nil pointer dereferences. After this, pointer bugs stop being guesswork.
- Responsible
- Jay P
- Last Update
- 11/27/2026
- Reading Time
- 4 min
Reviews
Sign in to write a reviewComments
Sign in to commentNo comments yet.