A pointer is used to store the address of some other variable.
So far, we have seen, how can we declare a variable.
And for every variable there is a memory location. The same way the house you live in has an address, the same way, the memory location of a variable also has an address.
Say for example, the variable 'num' has the address, '1087'(Just for our understanding). 'num' is just a name. The value '5' resides in the address '1087'.
Now, what if you want to declare a kind of variable that would hold the address of the variable 'num'. And this is exactly where pointer type of variable comes into picture.
A pointer variable would hold the address of some variable.
A Pointer type variable declaration would be just like a normal variable declaration. The only additional thing is, you need to put an asterisk '*' followed by the data type of the variable's address you want to hold.
Sounds little complicated? Let's simplify with the below example.
package main import "fmt" func main() { num := 5 var numPtr *int numPtr = &num fmt.Println("The value is :", *numPtr) }
So, in the above code, we have declared a variable 'num' and assigned the value '5' to it.
Let us say the address where 'num' variable resides is '1087'.
Now, we declare a pointer type variable that is going to hold the address of the integer type variable 'num.'
So, just remember, the int of '*int' is the data type of the variable 'num'.
In the next line, we are assigning the address of 'num'(i.e. '1087') to the pointer type variable 'numPtr'.
Again just remember, '&num' gives the address of 'num'.
Now, in other words, we can say that the pointer type variable 'numPtr' is pointing to the value of 'num', i.e. '5'.
And to print the value '5', we can use asterisk '*' followed by the pointer variable name (i.e. '*numPtr').
And that's what we have done in the next line.
And we get the below output.