Golang: The easy way to understand Golang Pointer thru example


Pointers reference a location in memory where a value is stored rather than the value itself. (They point to something else)

I write down my learning experiences about  Golang’s Pointer using easy way, here is my note:

The first step we have to understand  & and * operators:

 & and * Operators :

package main

import "fmt"

func do(x *int) {
	*x = 99 // Update x value
}

func main() {
	x := 5

	do(&x) // pass address of x

	fmt.Println(x) // The value updated through pointer
}

Output:

99

More example about pointer and operators

package main

import "fmt"

func do(x *int) {
	*x = 99
}

func main() {
	x := 5

	y := &x

	fmt.Println(&x) // Address of x
	fmt.Println(y)  // Address of x
	fmt.Println(&y) // Address of y that stores x Address

	do(y)

	fmt.Println(x)
}

Output:

0xc42000a3b0 // Address of x

0xc42000a3b0 // Address of x

0xc420032020 // Address of y that stores x Address

99  // x new value after updated thru pointer

Print x value thru pointer y:


package main

import "fmt"

func do(x *int) {
	*x = 99
}

func main() {
	x := 5

	y := &x

	fmt.Println(*y)
}

Output:

5

Another example: https://tour.golang.org/moretypes/1

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s