Skip to content
Codewilds

Lesson 22 of 38 · Structs & Methods

Go Pointers Explained: & and *

medium20 XP4 min read

Every time you pass a value to a Go function, the function receives a copy. That keeps code predictable, but sometimes you want a function to change the caller's variable: level up a player, swap two numbers, update a record. That's what pointers are for.

A pointer doesn't store a value itself — it stores the address of a variable, the place in memory where the value lives. Whoever holds the pointer can reach that variable to read or change it.

& and *: addresses and dereferencing

package main

import "fmt"

func main() {
	score := 10
	p := &score // p has type *int: "pointer to int"

	fmt.Println(*p) // read through the pointer
	*p = 20         // write through the pointer
	fmt.Println(score)

	score++
	fmt.Println(*p)
}
10
20
21
  • &score takes the address of score. Its type is *int, read "pointer to int". Every type has a pointer type: *string, *Player and so on.
  • *p dereferences the pointer: it is the variable p points to, so you can read it or assign to it.

p and score now refer to the same memory, so a change made through one is visible through the other. Printing p itself shows a memory address such as 0xc000012080, which changes from run to run.

nil pointers and new

The zero value of every pointer type is nil — a pointer that points nowhere. Dereferencing nil crashes the program:

var p *int
fmt.Println(p == nil) // true
fmt.Println(*p)       // panic: runtime error: invalid memory address or nil pointer dereference

Whenever a pointer might be nil, check it before you use it: if p != nil { ... }.

The built-in function new(T) creates a zero value of type T and returns a pointer to it. For structs you'll more often write &Player{...}, which does the same but lets you fill in fields:

n := new(int) // *int pointing to 0
*n += 5
fmt.Println(*n) // 5

Letting a function change your variable

Go always passes arguments by value. A function that receives an int can only change its own copy; a function that receives a *int can change the original:

func doubleCopy(n int) {
	n *= 2 // changes the local copy only
}

func double(n *int) {
	*n *= 2 // changes the caller's variable
}

func main() {
	x := 21
	doubleCopy(x)
	fmt.Println(x) // 21
	double(&x)
	fmt.Println(x) // 42
}

The & at the call site makes the intent visible: anyone reading double(&x) knows that x may change.

Pointers to structs

Pointers are used most often with structs. Go dereferences a struct pointer for you when you access a field: p.Level is shorthand for (*p).Level.

type Player struct {
	Name  string
	Level int
}

func promote(p *Player) {
	p.Level++ // same as (*p).Level++
}

func newPlayer(name string) *Player {
	return &Player{Name: name, Level: 1}
}

func main() {
	bo := newPlayer("Bo")
	promote(bo)
	fmt.Println(bo.Name, bo.Level)
	fmt.Println(*bo, bo)
}
Bo 2
{Bo 2} &{Bo 2}

For a pointer to a struct, fmt prints & followed by the fields instead of a raw address. Returning a pointer to a value created inside a function is perfectly safe in Go: the garbage collector keeps the value alive for as long as anything points to it.

When to use pointers

Use a pointer when a function must modify its argument, when a struct is large and copying it on every call would be wasteful, or when "no value" (nil) is a meaningful answer. Don't use pointers just because you can: small values such as an int, a string or a two-field struct are cheap to copy, and a value can't be changed behind your back. Slices and maps already share their data internally, so you rarely need pointers to them.

Unlike C, Go has no pointer arithmetic: p++ on a pointer is a compile error. A Go pointer always points to a real variable or is nil, which makes pointers far safer than in C.

Common mistakes

  • Dereferencing nil: p.Level++ with a nil p crashes the program. Check p != nil whenever nil is possible.
  • Forgetting &: double(x) doesn't compile — cannot use x (variable of type int) as *int value.
  • Re-pointing instead of writing: inside a function, n = &other only changes the function's own copy of the pointer, so the caller sees nothing. Write through it with *n = other.
  • Pointers everywhere: a pointer to a small value is rarely faster than the value itself, and it is always harder to follow.

Assignment

The starter declares a Player type:

type Player struct {
	Name  string
	Level int
	XP    int
}

Write four functions:

  1. Swap(a, b *int) swaps the values a and b point to. After x, y := 1, 2 and Swap(&x, &y), x is 2 and y is 1.
  2. ValueOr(p *int, fallback int) int returns the value p points to, or fallback if p is nil. A pointer to 0 is not nil, so it returns 0.
  3. NewPlayer(name string) *Player returns a pointer to a new Player with that name, Level 1 and XP 0.
  4. LevelUp(p *Player) adds 1 to the player's Level and resets XP to 0. For a nil player it does nothing — and must not panic.
ada := NewPlayer("Ada")
ada.XP = 80
LevelUp(ada)
fmt.Println(*ada) // {Ada 2 0}
LevelUp(nil)      // no effect, no panic

Premium lesson

Unlock the full Learn Go course

  • All 38 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 9 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Keep learning

Need a quick reminder? The Go cheat sheet has every topic of Learn Go on one page.

Lesson last updated on .

Write code ↓
Go+20 XP

Lesson 22 is part of the full course. The first 9 lessons are free.

Premium lesson

Unlock the full Learn Go course

  • All 38 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 9 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.