WeCodeAcademy

Go Pointers

A pointer holds the address of a value. &x takes the address; *p reads or writes through a pointer. Go passes arguments by value, so use a pointer when a function must change the caller's variable.

ExampleGo
package main

import "fmt"

func addOne(n int) { n++ }
func addOnePtr(n *int) { *n++ }

type Counter struct{ Count int }

func main() {
  x := 10
  addOne(x)
  fmt.Println(x) // 10: only a copy changed
  addOnePtr(&x)
  fmt.Println(x) // 11

  p := &x
  *p = 50
  fmt.Println(x, *p)

  c := &Counter{}
  c.Count++ // Go follows the pointer for you
  fmt.Println(c.Count)

  var none *int
  fmt.Println(none == nil)
}
Output
10
11
50 50
1
true
Quick check

Why pass a pointer to a function?

Finish the quick check (and any code exercise) to complete this lesson, or mark it done yourself.

Tip: use the left and right arrow keys to move between lessons.