Skip to main content
In this article, we explore how to declare and initialize pointers in Go. Understanding pointers is essential for managing memory addresses directly, which can lead to more efficient code.

Declaring a Pointer

A pointer holds the memory address of a variable. In Go, you can declare a pointer using the following syntax:
For example, to declare an integer pointer, you would write:
Similarly, you can declare a string pointer alongside an integer pointer:

Complete Example: Declaring Pointers

Below is a complete example illustrating the declaration of an integer pointer and a string pointer within the main function. When executed, the pointers will display their zero value, which is nil.
The output confirms that uninitialized pointers in Go have the nil value.

Initialising a Pointer

Once a pointer is declared, you must initialize it by assigning the memory address of an existing variable. There are several methods to do this.

Method 1: Using the Address Operator (&)

The first method uses the address operator (&) to assign the pointer the address of a variable:
For instance, to initialize a pointer to an integer:
Here, the variable i has a value of 10, and its memory address is stored in ptr_i.

Method 2: Type Inference

Go supports type inference, which allows you to omit the explicit data type. The compiler automatically determines the correct type:
For example, to initialize a pointer to a string variable:

Method 3: Shorthand Declaration Operator

You can also use the shorthand declaration operator to initialize a pointer. This approach eliminates the need for the var keyword:
For example:

Complete Example: Initialising Pointers

Below is an example that demonstrates all three methods together. In this program, we declare a string variable s and initialize three pointers (a, b, and c) to store its address. All three pointers will reference the same memory location.
When you run this program, you should see three identical memory addresses as output:
Pointers store the memory address of another variable, allowing you to manipulate data directly.
That concludes our guide on declaring and initializing pointers in Go. Keep exploring to further enhance your Go programming skills!

Watch Video