Pointers in Go

It's taken me ages to grasp pointers in Go. Every Youtube I have watched on it has frankly sucked and overexplained.

This blog post does a really good job of dumbing it down.

I will paraphrase it simply below:

Pointers in go

  • Go makes use of two special characters, the asertisk (*) and the ampersand (&).
  • Variables in progamming are really labels to pieces of data we need in our programs.
  • Variable values are stored in memory addresses

The asterisk (*)

  • The asterisk (*) in Go allows us to instead of passing around the whole chunk of data, we can instead say "this is the location of this peice of data in memory. If you need to get the data, use this memory address"
  • The asterisk allows us to dereference the memory address, i.e get the value at the memory address:
x := 10
fmt.Println(*x) // 10
*x = 20; // Changes x through the pointer

The asertisk does two things in Go: it declares a type as a pointer, but it also allows you to dereference the pointer

The ampersand (&)

  • The ampersand (&) is like a function that returns the memory address of the thing directly following it
x := 10
p := &x // p holds the memory address of x
fmt.Println(p) // prints a memory address e.g. 0x1400000e0a8
  • When a function expects a pointer, instead of passing the variable, you pass the memory address with the ampersand:
func expectsPointer(p *somePointerType) {
    // does something
}  

func main() {
    x := 10 
    expectsPointer(&x)
}