Go Tutorial · Data Structures · Lesson 16 of 30

Go Pointers

Addresses with & and *, passing by pointer, and nil.

What is a pointer?

A pointer holds the memory address of a value. &x takes the address; *p reads or writes the value it points to:

Example 1
package main

import "fmt"

func main() {
	x := 10
	p := &x
	fmt.Println(*p)
	*p = 20
	fmt.Println(x)
	var q *int
	fmt.Println(q == nil)
	n := new(int) // allocates a zero int, returns *int
	*n = 5
	fmt.Println(*n)
}

Output

10
20
true
5

Run this on your computer — see “Get Started” for setup.

Why pointers?

Go passes arguments by value — a function gets a copy. Pass a pointer when the function must modify the caller's value, or to avoid copying a large struct:

Example 2
package main

import "fmt"

type Counter struct{ N int }

func incrementCopy(c Counter) { c.N++ }

func incrementPtr(c *Counter) { c.N++ }

func main() {
	c := Counter{}
	incrementCopy(c)
	fmt.Println("after copy:", c.N)
	incrementPtr(&c)
	fmt.Println("after pointer:", c.N)
}

Output

after copy: 0
after pointer: 1

Run this on your computer — see “Get Started” for setup.

There's no pointer arithmetic in Go, and the garbage collector frees memory for you. Dereferencing a nil pointer panics.

Test yourself

Which operator gets the address of a variable?

  1. *
  2. &
  3. @
  4. ->
Show answer

Answer: &