Pointers
What you will learn
Pointers have a reputation for being hard, but the practical question behind them is simple: should a function work with a copy of a value, or with the original? This lesson explains values and copies first, then introduces the two pointer operators, shows how to change a caller's variable, and explains nil, the most common pointer pitfall.
A pointer is a value that holds the memory address of another value. You can think of a variable as a labelled box, and a pointer as a note that says which box to look in.
Values are copied
Whenever you assign a variable or pass it to a function, Go copies it:
age := 20
copiedAge := age
copiedAge = 30
fmt.Println(age) // 20
fmt.Println(copiedAge) // 30
Changing copiedAge does not touch age, because they are two separate boxes holding the same number. The same thing happens with function parameters, which is why double(n int) in the functions lesson could not change the caller's variable.
This also applies to structs, however large they are. Passing a struct with 20 fields copies all 20.
Taking an address with &
The & operator gives you the address of a variable:
age := 20
agePointer := &age
fmt.Println(agePointer) // an address such as 0xc0000120f0
fmt.Println(*agePointer) // 20
The type of agePointer is *int, read "pointer to an int". The exact address you see will differ on every run, and you will rarely print one.
Following a pointer with *
The * operator in front of a pointer follows it to the value it points at. This is called dereferencing. You can read through it or write through it:
age := 20
agePointer := &age
*agePointer = 21
fmt.Println(age) // 21
agePointer and age lead to the same box, so changing the value through the pointer changes age.
* symbol appears in two roles. In a type, as in var p *int, it means "pointer to". In an expression, as in *p, it means "the value that p points to".Letting a function change your variable
Here is the problem pointers solve. This function does nothing useful:
func celebrateBirthday(age int) {
age++ // changes only the local copy
}
Pass a pointer and the function can reach the original:
func celebrateBirthday(age *int) {
*age = *age + 1
}
func main() {
age := 20
celebrateBirthday(&age)
fmt.Println(age) // 21
}
The caller writes &age to say "I am handing over access to this variable". Notice that the pointer itself is still passed by copy, but the copy points to the same place.
Pointers and structs
Pointers are very common with structs, because methods often need to change the struct they belong to, and copying a big struct each call is wasteful:
type Account struct {
Balance int
}
func (a *Account) Deposit(amount int) {
a.Balance += amount
}
func main() {
acct := Account{Balance: 100}
acct.Deposit(50)
fmt.Println(acct.Balance) // 150
}
Two conveniences are at work. Go lets you write a.Balance instead of (*a).Balance when a is a pointer. And when you call acct.Deposit(50) on an addressable variable, Go automatically passes &acct. The structs lesson covers receivers in detail.
Creating pointers
Besides &variable, you can take the address of a struct literal directly, or use new:
p1 := &Account{Balance: 100} // pointer to a new Account
p2 := new(int) // pointer to a new int, starting at 0
*p2 = 7
It is safe to return a pointer to a local variable from a function. Go keeps the value alive as long as something points to it:
func newAccount() *Account {
acct := Account{Balance: 0}
return &acct
}
Programmers coming from C often worry about this, but Go's garbage collector handles it.
nil pointers
A pointer that points at nothing has the value nil, which is also the zero value for pointers:
var score *int
fmt.Println(score == nil) // true
Following a nil pointer crashes the program:
fmt.Println(*score)
panic: runtime error: invalid memory address or nil pointer dereference
This is the most common pointer bug in Go. Check before you dereference whenever nil is possible:
if score != nil {
fmt.Println(*score)
}
A nil pointer is sometimes useful on purpose, to mean "no value provided", for example an optional field.
When to use a pointer
Use a pointer when:
- the function or method must change the original value;
- the value is large and copying it repeatedly would be wasteful;
nilhas a meaningful role, such as "not set".
Prefer a plain value when:
- the data is small, like numbers, booleans, or short structs;
- you want the function to work on its own copy;
- you want the code to be easier to reason about, since a value cannot be changed from afar.
What Go pointers cannot do
Go has no pointer arithmetic. You cannot add 1 to a pointer to step through memory the way you can in C. That restriction is deliberate: it prevents a large family of memory bugs and lets the garbage collector track values reliably.
Common mistakes
- Dereferencing a nil pointer. Always consider whether a pointer can be
nil. - Forgetting
&when calling a function that expects a pointer. The compiler reports a type mismatch such ascannot use age (variable of type int) as *int value. - Expecting a value parameter to change the caller's variable. It is a copy.
- Sharing one pointer between many places by accident. If two structs hold the same pointer, changing it through one changes it for both.
Practice
Create a Player struct with Name and Score fields. Write an AddPoints method with a pointer receiver. Create a player, add points twice, and print the final score. Then write a second version with a value receiver and observe the difference.
package main
import "fmt"
type Player struct {
Name string
Score int
}
// Pointer receiver: changes the original Player.
func (p *Player) AddPoints(points int) {
p.Score += points
}
// Value receiver: changes only a copy.
func (p Player) AddPointsCopy(points int) {
p.Score += points
}
func main() {
player := Player{Name: "Mira"}
player.AddPoints(10)
player.AddPoints(5)
fmt.Println(player.Score) // 15
player.AddPointsCopy(100)
fmt.Println(player.Score) // still 15
}
AddPoints receives the address of player, so p.Score += points updates the original and the score becomes 15. AddPointsCopy receives its own copy, so the +100 is lost when the method returns. This is the same difference you saw between celebrateBirthday(age *int) and celebrateBirthday(age int).
Summary
Go copies values when you assign them or pass them to functions, so a function normally works on its own copy. & gives the address of a variable and * follows a pointer to the value, so passing &x lets a function change the caller's x. A pointer that points nowhere is nil, and dereferencing it panics, so check when nil is possible. Use pointers for mutation, large values, or optional values, not automatically everywhere.
Official reference: A Tour of Go: Pointers.
Ready to wrap up?
Mark this complete when you can explain the main idea and finish the practice task.