Cyberithub

How to Use Pointers in Golang [Complete Tutorial]

Advertisements

In the previous tutorial, we have seen how to work with arrays in Golang. In this tutorial, we will see how to use pointers in Golang. In programming, a pointer is referred to as a special variable which stores the memory address of other variables. In this article, we will explore pointers in Go and its application to solving problems. We will also look at some of the problems that could occur when working with pointers and how to mitigate them.

 

Prerequisites

 In order to follow through this article:-

  • You need to have a basic understanding of programming.
  • You need to download the Go compiler from the official website and follow the directions to install it based on your operating system being either Windows, MacOS or any of the Linux distributions.
  • You need a code editor like visual studio, atom or sublime text. Alternatively, you can download an Integrated Development Environment (IDE). An IDE is an improved code editor with added qualities customized to help you write and execute codes easier. Goland is the most popular IDE used for developing Go programs.
  • You need to have an understanding of Go basic data types like int, strings, structs and float.

How to Use Pointers in Golang [Complete Tutorial] 2

How to Use Pointers in Golang [Complete Tutorial]

Also Read: How to Work with Arrays in Golang [Complete Tutorial]

As we know, a variable is always stored in memory after it is declared. A pointer can be declared to store the memory address of this variable and refer to the value stored in it. Typically, a pointer is a special type of variable which stores the address of a variable in hexadecimal format (starting with 0x). In most programming languages, a pointer is defined to point to a variable of a certain type, therefore, it can only store the address of a variable storing that type.

In Go, pointers are mostly applied when trying to update the value of a variable from within a function. Before we dive deep into explaining pointers, let's briefly explain functions in Go.

 

Functions in Go

A function is a reusable block of code declared to perform some specific action. You can call a function in different parts of code to perform a specific action. In Go, a function is defined in the form:-

func function_name() {

            // function body

}

How to Use Pointers in Golang [Complete Tutorial] 3

In the picture above, we declared a function to print "Hello World!". We can call the function within main using function_name() as demonstrated below:-

How to Use Pointers in Golang [Complete Tutorial] 4

Output

How to Use Pointers in Golang [Complete Tutorial] 5

The main function is the default execution function in Go, and directs where the compiler should start reading code from. It cannot be declared and reused in any other part of code like other functions.

A function can also be declared to take in one or more parameters and return values of specific data-types. They are called by passing its argument within the parenthesis and assigning the result to a variable. The example below is a function which takes two numbers and returns their sum.

NOTE:

Please note that all the code samples used in this article were run on a 64-bit Ubuntu 20.04 Linux environment.

How to Use Pointers in Golang [Complete Tutorial] 6

Output

How to Use Pointers in Golang [Complete Tutorial] 7

 

Pointers in Go

In Go, a pointer is declared like a variable but with the asterisk (*) character before its data type in the form *T where T is that data type of the variable the pointer will point to. The asterisk character (*) is called a dereferencing operator in Go. It is used to denote a pointer type. The example below creates a pointer p which can store the address of an integer.

How to Use Pointers in Golang [Complete Tutorial] 8

The address-of operator (&) returns the address of a variable which can then be stored in a pointer. The address of variables in Go is usually in hexadecimal format. A pointer can only store the address of a variable of a data type which is equal to what the pointer was defined with.

How to Use Pointers in Golang [Complete Tutorial] 9

Output

How to Use Pointers in Golang [Complete Tutorial] 10

We can also declare and initialize a pointer on the same line. If we omit the data-type, the compiler will infer the pointer type from the address-of operator (&) and the data-type of the variable being addressed. Using the short variable declaration form, the compiler will also infer the pointer type as described above.

How to Use Pointers in Golang [Complete Tutorial] 11

 Output

How to Use Pointers in Golang [Complete Tutorial] 12

We can return the value of the variable a pointer points to by using the dereferencing operator (*) at the front of the pointer. This operation is called a dereferencing operation. It can also be used to indirectly update a variable.

How to Use Pointers in Golang [Complete Tutorial] 13

Output

How to Use Pointers in Golang [Complete Tutorial] 14

The zero value of a pointer is always Nil. A nil pointer is one which was declared but not initialized, meaning it does not point to any variable. Dereferencing a nil pointer will result in a panic because it does not point to any variable. It is advised to declare and initialize a pointer variable on the same line to prevent you from dereferencing a nil pointer mistakenly during practice.

How to Use Pointers in Golang [Complete Tutorial] 15

Output

How to Use Pointers in Golang [Complete Tutorial] 16

 

The new() function

The built-in function new() takes a data type, allocates some memory equivalent to that type and stores its zero value, then returns its memory address. It is a way of declaring a pointer type without first declaring a variable. Therefore, you have access to read or update that variable through only the pointer.

How to Use Pointers in Golang [Complete Tutorial] 17

Output

How to Use Pointers in Golang [Complete Tutorial] 18

 

Applying Pointers to Functions

When passing a variable to a function, a copy of that variable is declared in memory and passed to the function. Therefore, the function cannot make a change to the variable which was passed in as demonstrated below. This is called passing by value.

How to Use Pointers in Golang [Complete Tutorial] 19

Output

How to Use Pointers in Golang [Complete Tutorial] 20

In some practical cases, you will need to update a variable using a function. We can easily fix the code above to update the value of a from foo() by defining foo() to receive a pointer to int (*int) instead of an int, and passing a pointer to a into foo().  We then dereference a within foo() and change its initially stored value. This is called pass by reference.

How to Use Pointers in Golang [Complete Tutorial] 21

Output

How to Use Pointers in Golang [Complete Tutorial] 22

A practical example of where we could apply pass by reference and value is in a banking application. After making a withdrawal, a call to a withdraw function should accept a pointer to a variable storing the account balance of a user so it updates it to store the new balance. The price to be withdrawn can be passed by value since it does not change within the withdraw function.

How to Use Pointers in Golang [Complete Tutorial] 23

Output

How to Use Pointers in Golang [Complete Tutorial] 24

In the example above, we passed acctBal by reference into withdraw(). This way, we were able to update the value of acctBal from the function by dereferencing. We also passed price by value into withdraw() because we didn’t need to update it. Instead of creating a new pointer variable, acctBalPtr, and assigning the address of acctBal to it, we can more efficiently pass the address of acctBal into withdraw() by prefixing it with the address-of operator (&acctBal).

 

Conclusion

It is advised to take a pause when programming to determine if a pointer is necessary in a particular case or now. Misusing pointers can lead to changing memory values unnecessarily, or a panic when mistakenly dereferencing an uninitialized pointer. Aggregate data types like structs and arrays also have pointers which are applied when trying to change the value of its fields or index values respectively. When doing advanced programming, using pointers is inevitable because a lot of standard package functions in Go accept or return pointers.

Leave a Comment