Dereferencing Pointer in Go

Dereferencing a pointer means “accessing the value stored at the memory address the pointer holds”. To dereference a pointer in Go, you can use the “* operator” followed by the pointer variable. A pointer is a variable that stores the memory address of another variable.


package main

import "fmt"

func main() {
  // Declare an integer variable
  num := 21

  // Declare a pointer to an integer and assign the address of 'num'
  numPtr := &num

  // Print the value of 'num' using the pointer
  fmt.Println("Value of num using pointer:", *numPtr)

  // Modify the value of 'num' through the pointer
  *numPtr = 19

  // Print the modified value of 'num'
  fmt.Println("Modified value of num:", num)


Value of num using pointer: 21
Modified value of num: 19

In the above code, we first declared an integer variable num and assigned it the value 21.

In the next step, we declared a pointer to an integer, numPtr, and assigned it the address of num using the & operator.

To access the value stored at the memory address held by numPtr, we used the * operator followed by the pointer variable: *numPtr.

Then, we printed the value of num using the pointer and then modified the value of num through the pointer by assigning a new value to *numPtr.

Finally, we printed the modified value of num.

Leave a Comment