Lesson 10 of 20 · Part 3: Functions
Pointers
Go pointers explained for beginners. What & and * mean, passing pointers to functions, pointers to structs, nil pointers, new, and when to use a pointer.
4 min read · Updated · Beginner friendly
What you'll learn
- Understand what a pointer is, and what & and * do
- Let a function change a value by passing a pointer
- Use pointers to structs and avoid nil pointer crashes
- Decide when to use a pointer and when not to
Pointers have a reputation for being difficult, mostly because of languages like C, where you can do arithmetic with them and easily corrupt memory. Go’s pointers are much simpler and safer. There’s no pointer arithmetic, and memory is freed for you. A pointer in Go is just a way to say “that value over there” instead of making a copy.
What is a pointer?
Every variable lives somewhere in your computer’s memory, at an address. A pointer is a value that holds such an address. Two operators are all you need:
&x(“address of x”) gives you a pointer tox.*p(“the value p points to”) follows the pointer to reach the value.
package main
import "fmt"
func main() {
score := 10
p := &score // p points to score
fmt.Println("score:", score)
fmt.Println("value via p:", *p)
*p = 25 // change the value p points to
fmt.Println("score is now:", score)
fmt.Printf("type of p: %T\n", p)
}score: 10
value via p: 10
score is now: 25
type of p: *intp doesn’t hold 10; it holds the location of score. Writing through *p changes score itself. The type of p is *int, read as “pointer to int”.
If you print p directly you get the address in hexadecimal, something like 0xc000012345. The exact number changes on every run and isn’t something you need to care about.
Why pointers? Changing a value inside a function
In the last lesson you saw that function arguments are copies. A pointer is how a function can change a variable that belongs to its caller:
package main
import "fmt"
func resetCopy(n int) {
n = 0 // changes the function's own copy only
}
func reset(n *int) {
*n = 0 // changes the caller's variable
}
func main() {
lives := 3
resetCopy(lives)
fmt.Println("after resetCopy:", lives)
reset(&lives)
fmt.Println("after reset:", lives)
}after resetCopy: 3
after reset: 0The pointer itself is still copied, but the copy points at the same variable, so *n = 0 reaches the original.
Pointers to structs
Pointers are most often used with structs. Go lets you access fields through a pointer with a plain dot. You don’t need to write (*p).Field:
package main
import "fmt"
type Account struct {
Owner string
Balance float64
}
func deposit(a *Account, amount float64) {
a.Balance += amount // same as (*a).Balance += amount
}
func main() {
acc := Account{Owner: "Ada", Balance: 100}
deposit(&acc, 50)
fmt.Println(acc.Owner, acc.Balance)
// You can also create a struct and take its address in one step
shared := &Account{Owner: "Team", Balance: 0}
deposit(shared, 20)
deposit(shared, 30)
fmt.Println(shared.Owner, shared.Balance)
}Ada 150
Team 50&Account{...} creates a new struct and gives you a pointer to it. This is very common when a value will be passed around and updated in several places.
Is it safe to return a pointer to a local variable?
Yes. In C this is a classic bug, but in Go the compiler notices that the value is still in use and keeps it alive. Functions like func NewAccount(owner string) *Account { return &Account{Owner: owner} } are normal, idiomatic Go.
nil pointers
A pointer that doesn’t point anywhere has the zero value nil. Following a nil pointer crashes your program, so check before you use a pointer that might be nil:
package main
import "fmt"
type User struct {
Name string
}
func describe(u *User) string {
if u == nil {
return "no user"
}
return "user " + u.Name
}
func main() {
var nobody *User // nil
someone := &User{Name: "Grace"}
fmt.Println(describe(nobody))
fmt.Println(describe(someone))
}no user
user GraceWithout the nil check, u.Name would stop the program with panic: runtime error: invalid memory address or nil pointer dereference. This is the most common runtime crash in Go, so it’s worth recognising the message.
new
The built-in new(T) allocates a zero value of type T and returns a pointer to it:
package main
import "fmt"
func main() {
count := new(int) // *int pointing to 0
*count += 5
fmt.Println(*count)
}5In practice, &T{} is more common for structs, and new is mostly used for basic types.
Slices and maps already behave like references
You don’t need pointers to let a function change the elements of a slice or the entries of a map. A slice header points at its underlying array, and a map variable refers to the map’s data, so changes made inside a function are visible to the caller:
package main
import "fmt"
func doubleAll(nums []int) {
for i := range nums {
nums[i] *= 2
}
}
func addDefault(settings map[string]string) {
settings["theme"] = "dark"
}
func main() {
nums := []int{1, 2, 3}
doubleAll(nums)
fmt.Println(nums)
settings := map[string]string{}
addDefault(settings)
fmt.Println(settings)
}[2 4 6]
map[theme:dark]One exception: append inside a function may create a new array, and the caller won’t see the new length. Return the new slice instead (nums = addItem(nums, x)), just as append itself does.
When should I use a pointer?
Use a pointer when:
- a function needs to change the value it receives,
- the struct is large and copying it on every call would be wasteful,
- you need to represent “no value” with
nil, - the value must be shared so that everyone sees the same updates (for example, a counter or a connection).
Don’t use a pointer when:
- the value is small and read-only (numbers, small structs, strings),
- it’s a slice, map or channel: these are already cheap to pass around.
When in doubt, start without a pointer. Code that works with plain values is easier to reason about.
Exercises
1. Swap. Write swap(a, b *int) that swaps the values of two integer variables.
Show solution
package main
import "fmt"
func swap(a, b *int) {
*a, *b = *b, *a
}
func main() {
x, y := 1, 2
swap(&x, &y)
fmt.Println(x, y)
}2 12. Level up. Define type Player struct { Name string; Level int } and a function levelUp(p *Player) that adds one level. Call it twice and print the player.
Show solution
package main
import "fmt"
type Player struct {
Name string
Level int
}
func levelUp(p *Player) {
p.Level++
}
func main() {
hero := Player{Name: "Gopher", Level: 1}
levelUp(&hero)
levelUp(&hero)
fmt.Printf("%+v\n", hero)
}{Name:Gopher Level:3}3. Constructor. Write newCounter(start int) *int that returns a pointer to a new integer holding start. Increase the value through the pointer and print it.
Show solution
package main
import "fmt"
func newCounter(start int) *int {
n := start
return &n // safe in Go: n lives on after the function returns
}
func main() {
c := newCounter(10)
*c++
*c++
fmt.Println(*c)
}12Recap
- A pointer holds the address of a value.
&xtakes an address;*pfollows a pointer. - Pass a pointer when a function must change its caller’s value.
- Fields of a struct pointer are accessed with a plain dot:
p.Field. - The zero value of a pointer is
nil; dereferencing nil panics, so check first. - Slices and maps already share their data; prefer plain values unless you need a pointer.
Next: how Go handles things going wrong, with errors.
Finished this lesson?
Your progress is saved in this browser only.