WEB DEVELOPER SITE
HTMLCSSJAVASCRIPTSQLPHPBOOTSTRAPJQUERYANGULARXML
 

Go - Pointers


Pointers in Go are easy and fun to learn. Some Go programming tasks are performed more easily with pointers, and other tasks, such as call by reference, cannot be performed without using pointers.

every variable is a memory location and every memory location has its address defined which can be accessed using ampersand (&) operator, which denotes an address in memory.

package main

import "fmt"

func main() {
   var a int = 10   
   fmt.Printf("Address of a variable: %x\n", &a  )
}
When the above code is compiled and executed, it produces the following result Address of a variable: 10328000 So you understood what is memory address and how to access it. Now let us see what pointers are.

Use of Pointers

There are a few important operations, which we frequently perform with pointers: (a) we define pointer variables, (b) assign the address of a variable to a pointer, and (c) access the value at the address stored in the pointer variable.

package main

import "fmt"

func main() {
   var a int = 30   /* actual variable declaration */
   var ip *int      /* pointer variable declaration */

   ip = &a  /* store address of a in pointer variable*/

   fmt.Printf("Address of a variable: %x\n", &a  )

   /* address stored in pointer variable */
   fmt.Printf("Address stored in ip variable: %x\n", ip )

   /* access the value using the pointer */
   fmt.Printf("Value of *ip variable: %d\n", *ip )
}
$go run main.go
Address of a variable: c42000e1f8
Address stored in ip variable: c42000e1f8
Value of *ip variable: 30

Go Pointers in Detail

There are important concepts related to pointer which should be clear to a Go programmer −

Sr.No Concept & Description
1 Go - Array of pointers

You can define arrays to hold a number of pointers.

2 Go - Pointer to pointer

Go allows you to have pointer on a pointer and so on.

3 Passing pointers to functions in Go

Passing an argument by reference or by address both enable the passed argument to be changed in the calling function by the called function.