Go — pointers (basics)

Nikolaj Johannes Skole Jensen
2 min readJun 25, 2022

--

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”):

--

--

Nikolaj Johannes Skole Jensen
Nikolaj Johannes Skole Jensen

Written by Nikolaj Johannes Skole Jensen

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

No responses yet