Pointers and Memory Basics
Understand Go pointers (&x and *p), nil pointer safety, and when to pass values vs. pointers. After this, pointer errors stop being guesswork.
Course content
Sign in to save your progress.
-
Before You Write Code
-
Why Go Exists and When to Pick It
-
Run Your First Go Program
-
-
-
Values, Control Flow, and Functions
-
Variables, Types, and Zero Values
-
If, For Loops, and Multiple Return Values
-
-
-
Slices, Maps, and Structs
-
Arrays, Slices, and Why append Matters
-
Maps, Structs, and Pointer Receivers
-
-
-
Errors, Packages, and Testing
-
Handle Errors Without Hiding Them
-
Packages, Exports, and go test
-
-
-
Files, JSON, and a Small HTTP Server
-
Read Files and Decode JSON Structs
-
Build and Test a Small net/http Server
-
-
-
Pointers, Modules, and CLIs
-
Pointers and Memory Basics
-
Managing Dependencies and internal/ Packages
-
Building CLIs With flag, os.Getenv, and Exit Codes
-
-
Every Go function call copies its arguments. When you pass an int or a struct by value, the function modifies its own local copy and leaves the caller's variable untouched. Pointers (& and *) solve two real problems: letting a function mutate the caller's value in place, and representing "missing / not provided" cleanly as nil (for example, in partial JSON PATCH updates).
Skip ahead
If you already use &x and *p, guard against nil dereferences, and know when pointers distinguish omitted JSON fields from empty values, continue to "Managing Dependencies and internal/ Packages."
Experiment 1: Value copy vs. pointer mutation
Read the two pointer symbols as exact opposites: &n takes the memory address of n (producing type *int), and *x follows that address to read or write the underlying value:
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
Because doubleVal(n) received a copy of 10, multiplying x by 2 changed only that local variable. Passing &n to doublePtr pointed directly at n's slot in memory, so *x *= 2 updated n to 20.
Experiment 2: Why pointers matter in real APIs—PATCH updates with *string
Here is a real-world problem every API developer hits: suppose a client sends PATCH /users/7 with JSON to update only the fields they want to change. If your struct uses a plain Name string, you cannot tell the difference between {} (don't touch the user's name) and {"name":""} (explicitly clear the name)—both decode to ""!
Using a pointer field 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"
When "name" is absent, p.Name stays nil; when present, p.Name points to the decoded string (even if it is "").
Experiment 3: Guarding against nil pointer dereferences
The zero value of any pointer type is nil. Attempting to read or write *p when p == nil crashes immediately with runtime error: invalid memory address or nil pointer dereference. Any time a pointer can come from an optional JSON field, a lookup miss, or an uninitialized struct field, check if p != nil before dereferencing.
When to pass a value vs. a pointer
- Pass by value (
T) for small primitives (int,bool,string), small immutable structs (liketime.Time), and slices/maps/channels (their small headers already point to backing storage!). - Pass by pointer (
*T) when a function must mutate the caller's struct, when a struct contains async.Mutex(copying a lock breaks synchronization), or whennilmeans "not provided."
Common mistakes
- Passing
*[]Tor*map[K]Vunnecessarily: Slices and maps already reference their underlying data; only pass*[]Tif a function must replace the slice header itself without returning it. - Using pointers everywhere "for speed": Pointers often force Go's compiler to move values from the fast stack onto the garbage-collected heap, actually slowing down tight loops!
- Dereferencing optional JSON pointers without checking
!= nil: One missing field in a client request turns into an immediate500panic.
💡 Tip
Unlike C, Go forbids pointer arithmetic (p++ does not compile) and automatically moves variables to the heap if you return &localVar—so you can safely return pointers to local structs from constructors like func NewOrder() *Order { o := Order{}; return &o } without dangling-pointer bugs.
What happens if you skip this step
Guessing between values and pointers leads to methods that silently modify throwaway copies, PATCH endpoints that accidentally wipe fields to empty strings, and production panics from unchecked nil dereferences.
In a PATCH /profile endpoint, why does Bio *string work better than Bio string when users want to update their email without touching their existing bio?
About
Understand Go pointers (&x and *p), nil pointer safety, and when to pass values vs. pointers. After this, pointer errors stop being guesswork.
- Duration
- 5 min
- Last update
- 11/27/2026
Comments
Sign in to commentNo comments yet.