Pointers and Golang

Cheikh seck
2 min readOct 27, 2021

--

The first time I saw a pointer in Golang I treated it like any other variable. This was until I tried to log a pointer’s variable and I saw an interesting hexadecimal address. Prior to understanding how they worked, I wrote code in a different manner.

I'd always re-assign a variable after performing some changes. I can blame this bad habit on my misuse of the javascript concat method. Take a look at this code here :

func(){
...
myVar := Struct{}
myVar = ChangeSomething(myVar)
}

Absolutely barbaric, but this is how I handled most of my code. This code can be refactored to look more elegant without the use of pointers, but the focus of this article is about pointers.

The code sample above can be rewritten to use a pointer. The resulting code would be:

func(){
...
myVar := Struct{}
ChangeSomething(&myVar)
}

myVar is initialized as a struct, but it is passed into the function as a pointer. The pointer is a memory address that the function will be able to access. This means that the changes the function does to the variable are propagated back. The best use case I saw for this was with the built in xml library.

Just return an error

I found decoding XML in Go extremely challenging. But after gunning it and getting it to work, I understood the syntax better. The decoder would require you to pass a pointer to the struct variable you'd wish to have your data stored in. The function would return just an error, while the decoded data was already sent to your pointer.

Pointers and Concurrency

Concurrency is not the name of my new crypto, but rather performing multiple tasks at once. This is easily done on Golang with Goroutines. But what if I need to share data amongst concurrent processes? This is where pointers come into the picture. Channels could be used as an alternative, but variables have a much more universal application. Let’s say I had a server that utilised a variable to enable service, I can start a goroutine and pass the pointer in as an argument. This will enable me to control state without globals or a channel. The code below will illustrate how a pointer can be used to track an app’s state:

func server(str *bool){
...
}

func main(){
state := true
go server(&state)
...
}

Variable state can be modified by another Go routine and it will propagate to function server.

In essence, pointers are direct memory references of a variable. Although it is logged as an address, it behaves as any other variable. The example given above may yield runtime panics, this is due to the fact that certain variable types can’t be read and written at the same time. However, this can be worked around with thread locks.

--

--

Cheikh seck
Cheikh seck

Written by Cheikh seck

[Beta] Checkout my AI agents: https://zeroaigency.web.app/ Available for hire as a technical writer or software developer: cheeikhseck@gmail.com

No responses yet