[Go]Pointers

9Pointer is a variable that stores the memory address/register of the variable. If you extract the pointer variable without the asterix(*) sign, you will only get the register of the variable. In order to get the value you need to de-reference the pointer variable by using the asterix(*).

package main

import "fmt"

// function to change x to 100
func changevar(x int) {
	x = 100
}

// Pass in the x address
// then change the value where x is pointed to.
func changevar2(x *int) {
	*x = 100
}

func main() {
	// declare a pointer variable.
	// pointer variable stores address
	var ptr *int
	// the variable i stores the value of 100
	i := 100
	// ptr is assigned with the address of variable i.
	ptr = &i
	// this prints the register/address of i but not the value.
	fmt.Println(ptr)
	// to print out the value, you need to de-reference ptr by using *ptr
	fmt.Println(*ptr)

	// x is assigned with 50
	x := 50
	// attempt to change x to 100
	changevar(x)
	// x however is still 50
	// this is because the x that was passed into changevar() is a copy of the current x not the x itself.
	// in order to change the x, we need to pass in the
	fmt.Println(x)
	
	// Pass in the address of where x is pointed to.
	// value of x is changed to 100 by passing the value to the dereferenced x.
	changevar2(&x)
	fmt.Println(x)

}
Advertisement

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 )

Connecting to %s