A few words before we start. You can find the code used in this tutorial in this repository. You can find the full contents of Road to Go Pro here. If you missed the last one, you can find it via this link.

We talked about flow controls and loops in the last part of the tutorial. In this one, we will cover pointers and functions. After finishing the first 4 parts of Road to Go Pro, you are well equipped to start writing scripts or console applications using Go.

Pointers

Image for post

Photo by Nathalie SPEHNER on Unsplash

If you have used C or C++, you already know what’s a pointer. However, in the most popular programming languages like Java, C#, Javascript, Python, etc. there’s no explicit syntax to represent pointers. I had no idea what it is when I first heard of this name.

In short, a pointer holds the underlying memory address of a value. Whoa, hold on, memory address? Isn’t Go a high-level programming language?

When do we even need to know about the memory addresses of variables?

That’s a good question but before exploring the answer, we need to take a quick detour. Let’s see how to declare pointers and how to use them in functions. Once we have covered these, it will be easier for you to understand the reasoning and examples below. So hang in there.

Declaring pointers

Whenever we declare a variable in Go, the compiler allocates a segment of memory to store it. The value of that variable is stored there until it is recycled by the garbage collector.

Pointers are composite data types. We form a pointer type by adding an * in front of the data type it points to. For instance, *string represents the type of a pointer pointing to a string-type variable.

To get the pointer value of an existing variable, we need to add an & in front of the variable.

#golang #go #golang-tutorial #golang-development

Road to Golang pro — Pointer & Functions
2.45 GEEK