Open In App

How to declare and access pointer variable in Golang?

Last Updated : 10 May, 2020
Improve
Improve
Like Article
Like
Save
Share
Report

Pointers in Go programming language or Golang is a variable which is used to store the memory address of another variable. Pointers in Golang is also termed as the special variables. The variables are used to store some data at a particular memory address in the system. The memory address is always found in hexadecimal format(starting with 0x like 0xFFAAF etc.).

Before we start there are two important operators which we will use in pointers i.e.

* Operator also termed as the dereferencing operator used to declare pointer variable and access the value stored in the address.

& operator termed as address operator used to returns the address of a variable or to access the address of a variable to a pointer.

Declaring a pointer:

var pointer_name *Data_Type

Example: Below is a pointer of type string which can store only the memory addresses of string variables.

var s *string

Initialization of Pointer: To do this you need to initialize a pointer with the memory address of another variable using the address operator as shown in the below example:

// normal variable declaration
var a = 45

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

Example: In the following example, using pointer we will access the value of the variable whose address is stored in pointer.




// Golang program to show how to declare
// and access pointer variable in Golang
package main
  
import (
    "fmt"
)
  
func main() {
  
    // variable declaration
    var dummyVar string = "Geeks For Geeks"
  
    // pointer declaration
    var pointerVariable *string
  
    // assigning variable address to pointer variable
    pointerVariable = &dummyVar
  
    // Prints the address of the dummyVar variable
    fmt.Printf("\nAddress of the variable: %v", &dummyVar)
  
    // Prints the address stored in pointer
    fmt.Printf("\nAddress stored in the pointer variable: %v", pointerVariable)
  
    // Value of variable
    fmt.Printf("\nValue of the Actual Variable: %s", dummyVar)
  
    // Value of variable whose address is stored in pointer
    fmt.Printf("\nValue of the Pointer variable: %s", *pointerVariable)
}


Output:

Address of the variable: 0xc00010a040
Address stored in the pointer variable: 0xc00010a040
Value of the Actual Variable: Geeks For Geeks
Value of the Pointer variable: Geeks For Geeks

Explanation: Here (&) symbol is used to get the address of the variable storing the value as “Geeks for Geeks”. The address owned by this variable is the same which is stored in the pointer. Therefore, the output of &dummyVar and pointerVariable is the same. To access the value stored at the address, which is stored in pointer we user (*) symbol.


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads