Go Pointers

Go Language - Pointers

Pointers are used to store address of the memory allocation of a variable. The value of a Pointer denotes the address of the variable. Whenever the call by reference are performed the occurrence of pointer is must.

Syntax
var var_name *var_type;
var_name -name of the pointer
*  -used to declare a pointer
var_type –data type

Declaring a pointer:

Syntax
var a *int    /*pointer to an integer*/
var b *float32    /*pointer to a float*/

Data type of pointer :

The data type of a pointer is just to indicate the data type of the variable which address is get stored in the pointer’s value. The value of the pointer just contains a long hexadecimal number which represent the memory address.

How to use Pointers :

  • Defining a pointer variable
  • Assigning the address of a variable
  • Access the value of an assigned variable by using pointer

For example Program :

CODE/PROGRAM/EXAMPLE
package main       /* Main package */
import "fmt"      /* Importing fmt */
func main(){     /* Main function */
	var m float=50	/* actual variable */
	var p *float	/* pointer variable */
	p =&m   /* store address of m in p */
	fmt.Printf("Address of m: %x\n",&m  )
	/* Displays Address stored in pointer by using & */
	fmt.Printf("Address stored in p: %x\n",p )
	/* Displays Address stored in pointer by using p */
	}
	
Output:
Address of m: 16052601
Address stored in p: 16052601	

Retrieving the value of a variable by using pointer :

The value of the variable located at the address specified by the pointer can also get retrieved by the pointer variable. This can be done by using the unary operand *.

For example Program :

CODE/PROGRAM/EXAMPLE
package main       /* Main package */
import"fmt"      /* Importing fmt */
func main(){     /* Main function */
	var m float=50	/* actual variable */
	var p *float	/* pointer variable */
	p =&m   /* store address of m in p */
	fmt.Printf("Value of p: %d\n",*p ) 
	/* Displays value stored in p by using unary operand */
	}
	
Output:
Value of p: 50

Nil Pointers :

At the of time of pointer variable declaration since it as no exact address to display it is assigned as Nil value and that pointer is called as Nil pointer.

For Example Program :

CODE/PROGRAM/EXAMPLE
package main 
import"fmt"
func main(){
	var p *int
	fmt.Printf("Value of p: %x\n",p )
	}
Output:
Value of p: 0

Most of the OS doesn’t permits the program to access the memory at address 0. Due to convention the pointer gets Nil(0) value. To check the Nil pointer the following statements can be used:

CODE/PROGRAM/EXAMPLE
if(p != nil) /* succeeds if p is not nil */
if(p == nil) /* succeeds if p is null */
#Go_Language_Pointers #golang_pointers #golang_pointer #golang_function_pointer #golang_string_pointer #dereference_pointer_golang #golang_Declaring_a_pointer #golang_Data_type_of_pointer #golang_Nil_Pointers

(New page will open, for Comment)

Not yet commented...