Pointers

Much like C, Go supports pointers allowing you to reference specific memory locations and perform various memory manipulations

Pointers are different from values. Pointers return a memory location which we can use in various contexts. We can use the location to change the value stored at that location, or remove that value all together. In this section, we will cover some of the basic operations we can do with golang pointers.

pointers.go
package main

import "fmt"

func change_by_val(num int) {
  num = 10
}

func change_by_ptr(num *int) {
  *num = 23
}

func run_pointers() {
  num := 12
  fmt.Println("initial num:", num)

  change_by_val(num)
  fmt.Println("change by val:", num)

  change_by_ptr(&num)
  fmt.Println("change by pointer:", num)

  fmt.Println("pointer address:", &num)
}
$ go run pointers.go
initial num: 12
change by val: 12
change by pointer: 23
pointer address: 0xc0000180a8

Above, we declare two functions, change_by_val which takes an integer as input, and change_by_ptr which takes a pointer as argument. When we call the change_by_val function, it gets a copy of num distinct from the one in the calling function, hence why num never changes from 12 to 10 as it should.

However, when we declare change_by_ptr we set the parameter, num *int which means we are passing a pointer parameter. The code then dereferences the pointer from its address in memory to the current value at that address. So when the function is called later in the program with &num, we pass the memory address of num, i.e. a pointer to num which then changes the value at that address from 12 to 23.

Finally, we can print the pointer address (memory address) by using the fmt.Println method, passing &num to the print statement.

Last updated