Pointers

Go has pointers. A pointer holds the memory address of a value.

The type *T is a pointer to a T value. Its zero value is nil.

  1. var p *int

The & operator generates a pointer to its operand.

  1. i := 42
  2. p = &i

The * operator denotes the pointer's underlying value.

  1. fmt.Println(*p) // read i through the pointer p
  2. *p = 21 // set i through the pointer p

This is known as "dereferencing" or "indirecting".

Unlike C, Go has no pointer arithmetic.

pointers.go

  1. package main
  2. import "fmt"
  3. func main() {
  4. i, j := 42, 2701
  5. p := &i // point to i
  6. fmt.Println(*p) // read i through the pointer
  7. *p = 21 // set i through the pointer
  8. fmt.Println(i) // see the new value of i
  9. p = &j // point to j
  10. *p = *p / 37 // divide j through the pointer
  11. fmt.Println(j) // see the new value of j
  12. }