TExcelTAD
Home › Go › Go Pointers

Go Pointers

A pointer holds the memory address of a value instead of the value itself. Because Go passes everything by value (copies), pointers are how you let a function modify a variable that belongs to its caller, and how you share one large struct instead of copying it.

Go pointers are safe: there is no pointer arithmetic, and the garbage collector frees memory for you once nothing points to it.

& and *

Syntax Name Meaning
*T pointer type "pointer to a T", e.g. *int
&x address-of gives a pointer to the variable x
*p dereference the value that p points to (read or write)
go · try it yourself
package main

import "fmt"

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

	fmt.Println(*p)        // read through the pointer
	*p = 25                // write through the pointer
	fmt.Println(score)     // the original changed
	fmt.Printf("%T\n", p)
	fmt.Println(p == &score)
}
10
25
*int
true

Printing p itself would show a hexadecimal address like 0xc000012345 that changes from run to run, so this course prints the value behind it instead.

Pointers as function parameters

A function that receives a pointer can change the caller's variable. This is the classic use:

go · try it yourself
package main

import "fmt"

func addTen(n int) {
	n += 10 // changes a copy
}

func addTenPtr(n *int) {
	*n += 10 // changes the caller's variable
}

func swap(a, b *string) {
	*a, *b = *b, *a
}

func main() {
	x := 5
	addTen(x)
	fmt.Println(x)
	addTenPtr(&x)
	fmt.Println(x)

	first, second := "left", "right"
	swap(&first, &second)
	fmt.Println(first, second)
}
5
15
right left

nil pointers

The zero value of a pointer is nil — it points to nothing. Dereferencing a nil pointer causes a runtime panic, so check before you use a pointer that might be nil.

go · try it yourself
package main

import "fmt"

func describe(p *int) string {
	if p == nil {
		return "no value"
	}
	return fmt.Sprint("value ", *p)
}

func main() {
	var missing *int
	n := 7

	fmt.Println(missing == nil)
	fmt.Println(describe(missing))
	fmt.Println(describe(&n))
}
true
no value
value 7

new and pointers to structs

The built-in new(T) allocates a zeroed T and returns a *T. More often you will take the address of a struct literal: &Point{...}. When accessing fields through a struct pointer, Go dereferences automatically — p.X means (*p).X.

go · try it yourself
package main

import "fmt"

type Player struct {
	Name  string
	Level int
}

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

func main() {
	counter := new(int)
	*counter = 3
	fmt.Println(*counter)

	hero := &Player{Name: "Aria", Level: 1}
	levelUp(hero)
	levelUp(hero)
	fmt.Println(hero.Name, hero.Level)

	sidekick := Player{Name: "Bo"}
	levelUp(&sidekick)
	fmt.Printf("%+v\n", sidekick)
}
3
Aria 3
{Name:Bo Level:1}

Returning pointers to local variables is safe

In C, returning the address of a local variable is a bug. In Go it is perfectly fine: the compiler notices the value escapes and puts it on the heap, where it lives as long as something points to it.

go · try it yourself
package main

import "fmt"

type Config struct {
	Port  int
	Debug bool
}

func NewConfig() *Config {
	c := Config{Port: 8080} // local variable...
	return &c               // ...safely returned by address
}

func main() {
	cfg := NewConfig()
	cfg.Debug = true
	fmt.Printf("%+v\n", *cfg)
}
{Port:8080 Debug:true}

When should you use pointers?

Use a pointer when… Use a plain value when…
the function must modify the argument the function only reads it
the struct is large and copying would be wasteful the type is small (numbers, small structs)
you need to express "no value" with nil the zero value is a fine default
the type contains a sync.Mutex or similar that must not be copied the type is immutable

Note: Slices, maps and channels already contain references internally, so you rarely need pointers to them. Pass them by value.

Test yourself

If x := 4 and p := &x, what does *p = 9 do?

  1. Changes p to point to 9
  2. Sets x to 9
  3. Compile error
  4. Creates a new variable

What is the zero value of a pointer?

  1. 0
  2. nil
  3. An address of a zero value
  4. Undefined

Is returning &local from a function safe in Go?

  1. No, it is a dangling pointer
  2. Yes, escape analysis moves it to the heap
  3. Only for ints
  4. Only with new