Go — pointers (basics)

When discussing a pointer in CS (Computer Science), you usually talk about them being a construct that points to a given value by holding an address.

In Go pointers are used to pass references to specific values, thereby allowing for direct editing/updating/deleting of values by reference. For example, a function can use a pointer as one of its parameters, to have a reference for that specific value:

In the previous example, when using the function: “pointerExample”, I use an ampersand: “&value”. The ampersand is used to indicate a memory address hereby a pointer for the variable: “value”.

The typical use for pointers is to have a reference to a specific value for a given variable. This allows f.ex. a function to change that particular value in memory. Given our previous example, it takes in value instantiated to the value: 10. But in the function it takes the pointer/address of that variable, and changes the value in that specific address to 0:

If we changed the “pointerExample” function, to a “normal” function that doesn't accept a pointer, it would change the underlying behavior:

Take note of how the variable: “value”, doesn’t have Its value (10) changed by passing it on to the function: “normalExample”.

Using the ampersand, you can also print out the memory address for a given variable (here again: “value”):

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Nikolaj Johannes Skole Jensen

Fullstack developer living in Denmark. Experience with both Web- and App development.