Go: Pointers

Consider the following example, which will print the address of the variables definedĀ 

package main

import "fmt"

func main() {

   i, j := 42, 2701

   p := &i         // point to I
   fmt.Println(*p) // read i through the pointer
   *p = 21         // set i through the pointer
   fmt.Println(i)  // see the new value of I

   p = &j         // point to j
   *p = *p / 37   // divide j through the pointer
   fmt.Println(j) // see the new value of j
}

=> Ouput:

42
21
73

Declaring a pointer:

var var_name *var-type

Example:

var s *string /* pointer to a string */

Initialization of Pointer:

// normal variable declaration
var a = 45

// Initialization of pointer s with 
// memory address of variable a
var s *int = &a

Nil Pointers:

The nil pointer is a constant with a value of zero defined in several standard libraries.

Example:

package main

import "fmt"

func main() {
   // taking a pointer
   var  s *int

   // displaying the result
   fmt.Printf("s = ", s)
}

=> Output

s =  <nil>

Leave a Reply

Your email address will not be published. Required fields are marked *