Skip to Content
Skip to content
Go for Beginners: Write Reliable Programs and Small Services
Beginner
Courses
Go for Beginners: Write Reliable Programs and Small Services

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.

Course Home

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 (like time.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 a sync.Mutex (copying a lock breaks synchronization), or when nil means "not provided."

Common mistakes

  • Passing *[]T or *map[K]V unnecessarily: Slices and maps already reference their underlying data; only pass *[]T if 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 immediate 500 panic.

💡 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
Was this helpful?
​ 0 ​ 0

Comments

Sign in to comment

No comments yet.