Welcome To Golang By Example

* or dereferencing pointer in Go (Golang)

Table of Contents

Overview

* operator can be used to:

Program

package main

import "fmt"

func main() {
	a := 2
	b := &a
	fmt.Println(a)
	fmt.Println(*b)

	*b = 3
	fmt.Println(a)
	fmt.Println(*b)

	a = 4
	fmt.Println(a)
	fmt.Println(*b)
}

Output

2
2
3
3
4
4

Both a and *b refer to the same variable internally.  Hence the changing the value of one reflects in another. Also, * and & can be used together as well. But they will cancel out each other.

Hence below two are equivalent and will print 2

Also below three are equivalent and will print the address of variable a which is stored in b variable

Note:  *a is not a valid operation as a is not a pointer