Declaring a Pointer
A pointer holds the memory address of a variable. In Go, you can declare a pointer using the following syntax:Complete Example: Declaring Pointers
Below is a complete example illustrating the declaration of an integer pointer and a string pointer within themain 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:
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:Method 3: Shorthand Declaration Operator
You can also use the shorthand declaration operator to initialize a pointer. This approach eliminates the need for thevar keyword:
Complete Example: Initialising Pointers
Below is an example that demonstrates all three methods together. In this program, we declare a string variables and initialize three pointers (a, b, and c) to store its address. All three pointers will reference the same memory location.
Pointers store the memory address of another variable, allowing you to manipulate data directly.