Understanding pointers in Go

/ / understanding pointers in go

Updated: 2017-02-21

Hi there! It’s nearly impossible to work with Go without being exposed to pointers. I hope this article can help fellow developers understand how pointers work :)

How pointers work

A pointer holds the memory address of a value.

In Go, the type *T is a pointer to a T value, for which its zero value is nil.

var p *int

The & operator generates a pointer to its operand:

i := 7
p = &i

The * operator denotes the pointer’s underlying value:

fmt.Println(*p) // read i through the pointer p
*p = 8 // set i through the pointer p

This is known as dereferencing and indirecting.

package main

import "fmt"

func main() {
  var p *int
  i := 7
  p = &i
  fmt.Println(*p) // prints 7
  *p = 8
  fmt.Println(i) // prints 8
}

When and why we should use pointers

When calling a function that takes an argument, that argument is copied to the function:

package main
	
import "fmt"
	
func zero(i int) {
  i = 0
}

func main() {
  i := 7
  zero(i)
  fmt.Println(i) // prints 7
}

In the above code, we can see that the zero function will not modify the original i variable in the main function.

In order to achieve that, we could use pointers:

package main
	
import "fmt"
	
func zero(iPtr *int) {
  *iPtr = 0
}

func main() {
  i := 7
  zero(&i)
  fmt.Println(i) // prints 0
}

By referencing a location in memory where the value is stored rather than the value itself, pointers are able to modify the original variable.