Saturday 4 September 2021

Go Pointer

 A pointer is a variable that stores the address of another variable. The general form of a pointer variable declaration is:

  1. var var_name *var-type  

A newly declared pointer which has not been assigned to a variable has the nil value.

The address-of operator &, when placed before a variable gives us the memory address of the variable.

With pointers, we can pass a reference to a variable (for example, as a parameter to a function), instead of passing a copy of the variable which can reduce memory usage and increase efficiency.

Go Pointer Example 1

  1. package main  
  2. import (  
  3.    "fmt"  
  4. )  
  5. func main() {  
  6.    x:=10  
  7.    changeX(&x)  
  8.    fmt.Println(x)  
  9. }  
  10. func changeX(x *int){  
  11.    *x=0  
  12. }  

Output:

x = 0

Go Pointer Example 2

  1. package main  
  2. import (  
  3.    "fmt"  
  4. )  
  5. func main() {  
  6.    ptr := new(int)  
  7.    fmt.Println("Before change ptr",*ptr)  
  8.    changePtr(ptr)  
  9.    fmt.Println("After change ptr",*ptr)  
  10. }  
  11. func changePtr(ptr *int)  {  
  12.    *ptr = 10  
  13. }  

Output:

Before change ptr 0
After change ptr 10 


No comments:

Post a Comment