Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   




GO - POINTERS


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'.


num := 5

java_Collections

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.


How to declare a pointer type variable?


var numPtr *int

java_Collections

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.


Example :



package main  
import "fmt"
      
func main() {  
    
    num := 5
    var numPtr *int 
    numPtr = &num
    fmt.Println("The value is :", *numPtr)  
}


Output :



 The value is : 5

So, in the above code, we have declared a variable 'num' and assigned the value '5' to it.


num := 5

Let us say the address where 'num' variable resides is '1087'.


java_Collections

Now, we declare a pointer type variable that is going to hold the address of the integer type variable 'num.'


var numPtr *int

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'.


numPtr = &num

Again just remember, '&num' gives the address of 'num'.


java_Collections

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.


fmt.Println("The value is :", *numPtr)

And we get the below output.


The value is : 5