Pointers

A Pointer is a variable that holds address of another variable.

Consider an example of integer type variable num containing value 10

num := 10

If you want to get value of num then you can access it using identifier num and if you want to get address where value 10 is stored then you can use operator &, i.e. &num

fmt.Println(num) // 10
fmt.Println(&num) // 0Xc0420381do

Now declare a pointer variable p of integer type and assign it address of variable num

var p *int
p = &num

Now value of pointer p is address of variable num.

// Print value of pointer p
fmt.Println(p) // 0Xc0420381do

// Print address of p
fmt.Println(&p) // 0xc042022028

// Print value of variable num holded by pointer p
fmt.println(*p) // 10


Example

package main

import (
	"fmt"
)

func main() {
	// Declare an integer type variable
	var num int
	// Initialize value to variable
	num = 10

	// Print value and address of variable num
	fmt.Println(num, &num)

	// 	Declare a pointer that stores address of a interger
	var p *int
	// Store address of variable num to pointer variable
	p = &num

	fmt.Println(*p, p, &p)
	fmt.Println(num, &num)
}

Leave a Reply

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