Golang - Chapter 8



Pointers contain the memory address to a value instead of the value itself. To take the address of a variable, use &, e.g. x := &a. To access the value at an address, we use *, e.g. j=*a.

Before delving deeper, lets understand what is the meaning of passing by value as compared to passing by reference.

Pass by Value

If we have a function that takes in an int - f(x int) and if we have j:=5, and we call f(j), we first create a copy of j with a value of 5 and then pass it to f. Modifying the passed variable will not affect the original variable.

Pass by Reference

When we pass by reference, it means we pass the address of the variable, i.e. f(&j). The address of a variable refers to the memory address where the variable lives.

Memory Address

In the above image, we allocate a value of 10 to x and 12 to y. Now, the system chooses a memory location where it will store x and y. In this example, the system has chosen memory address 0 for x and 3 for y.

When we pass by reference, we will not pass x, but rather the address of x, which is 0 in this example. Now, at address 0, we hold the value 10. Hence, modifying the contents of an address will mean we modify what is stored there, and hence, the value of x will be modified as well.


func addOne(a *int) {
	*a += 1

func addTwo(a int) {
	a += 1

func main() {
	x := 10
	// before
	fmt.Println(x, &x)
	// does not modify the value of x
	fmt.Println(x, &x)
	// after - x is modified
	fmt.Println(x, &x)

// 10 0x10414020
// 10 0x10414020
// 11 0x10414020

In the above example, we have two functions: addTwo and addOne. addTwo takes an int while addOne takes the pointer to an int.

Testing with these two functions will show that the value of x is modified when passed to addOne as the function modifies the value stored at a particular memory address. In addTwo however, we created a copy of x and passed that copy, which means any changes made inside addTwo has no impact on the original variable x.

Harish V
Software Engineer + Tech Enthusiast

I code.

comments powered by Disqus