A crash course on Pointers in Go

Search for a command to run...

No comments yet. Be the first to comment.
Java 24 Stream Gatherers: A Modern Take on Stream Data Aggregation

Boost Performance in Java Apps with Virtual Threads in Java 21

Intro to Spring Cloud Circuit Breaker with Spring Boot 3.x, Java 17 & Resilience4j

Spring Cloud Service Discovery with Spring Boot 3.x, Java 17 & Spring Netflix Eureka

A quicker and neater way to create Data Transfer Object

Hey, fellow devs. Here we go with my first article. Let's hope you and I both enjoy the journey and we both end up getting better at something along the way. ;)
Today we're going to talk about one of the most confusing programming topics of all time! POINTERS!! What is that weird *-& thing doing in front of our beloved variables we named so carefully as "x", "y" or "thisIsVeryShortAndMeaningfulNameForMyVariable"?
This article is targeted as a starter for pointers in Go Lang. So in this, we're not really going to dive deep into technicalities and use cases. Here we'll simply talk about WHAT, and not about When and Why of pointers.
So let us very quickly take a look at a very short piece of code
When you execute this piece of code, you see this as the output:
X is ==> 10
xAddress is of type ==> *int
X is stored at the address ==> 0xc00001a0b8
Value stored at xAddress is ==> 10
So what happened here? To understand this, let's learn two very basic rules of pointers which(if remember correctly) I learned from the book Let Us C by Yashvant Kanetkar.
Let's apply these two rules to our code.
But what if we also want to have the address of the pointer variable itself? In simple terms, what if we need to know where is the variable itself, that holds the address, is living in the memory?
To answer this, let's add some more lines to our code
addressOfAddress := &xAddress
fmt.Printf("xAddress is stored at is ==> %v\n", addressOfAddress)
fmt.Printf("Value stored at addressOfAddress is ==> %v\n", *addressOfAddress)
This gives you the address of this new pointer variable that we created. If you check the older output, "Value stored at addressOfAddress " should give you the exact same address as we got for xAddress.
Now comes the fun part. If this variable can give me the address of another variable, is it also possible to get the value stored at the address stored in this "addressOfAddress" variable? Let's give it a shot!!
fmt.Printf("Value at the address stored at addressOfAddress is ==> %v\n", **addressOfAddress)
Voila!! We get the value of our initial integer variable x which was 10. This shows that we can also chain the pointers which can be useful in complex apps.
That's all for today folks. Hope you enjoyed reading the article and that I was able to explain the concept as short as possible while keeping it meaningful.
Till next time. Adios.
Oh, and feedback is always welcome. :)