Today I Learned: Working With Pointers in Golang

Tuesday July 28, 2020 at 08:23 pm CST

A pointer is an object that holds an address in memory. If you wanted to, for example, create an pointer that pointed to the memory address of an integer value, you would declare it like so:

var pointy *int

You can use the & operator in conjunction with a pointer to store the address of a variable. The & operator returns the memory address of its operand.

num := 20
pointy = &num

You can use the dereferencing operator * to retrieve the value stored at a memory address.

fmt.Println(*pointy)
// 20

You can also use the dereferencing operator to store values at a memory address.

*pointy = 77
fmt.Println(num)
// 77

One gotcha with pointers is that you must initialize them before attempting to store a value in them. The following code will not work:

func main() {
  var color *string

  *color = "navy"
}

// panic: runtime error: invalid memory address or nil pointer dereference...

You’ll have to designate a block in memory for the value to which the pointer will point. You can accomplish this using the new keyword. new(T) will allocate memory to a value of type T and then return the address of that space in memory, i.e. a value of type *T.

func main() {
  var color *string = new(string)
  *color = "navy"

  fmt.Println(*color)
}

// navy

Here’s a helpful article on pointers in Golang: Playing with Pointers in Golang


Photo by Jonny Caspari on Unsplash