Menu
Coddy logo textTech

Value vs Reference

Lesson 7 of 19 in Coddy's Functions and Pointers in Golang course.

Up to this point, we have learned how to use parameters and return values from functions. In this lesson, we will explain another important concept that we should understand when working with functions.

Let's consider a program like this:

func main() {
    a := 5
    fmt.Println("value of a:", a)
    sum(a)
    fmt.Println("value of a after addition:", a)
}
func sum(x int) {
    x = x + x
}

In this program, we declare a variable a, print its value, and then pass it to a function called sum. This function performs the addition 5 + 5. What do you think the result of this code will be?

Let's run it and see:

value of a: 5
value of a after addition: 5

There is no change. There is a problem here; a should be 10 after calling the sum function, right?

Well, no, because in Go, when we pass a value to a function, we only copy it, and when we make changes to the value, they don't appear outside the function. The value changes only inside the function. We can see this if we print the value inside the sum function:

func main() {
    a := 5
    fmt.Println("value of a:", a)
    sum(a)
    fmt.Println("value of a after addition:", a)
}
func sum(x int) {
    x = x + x
    fmt.Println("value inside the function:", x)
}

If we run this, we will get:

value of a: 5
value inside the function: 10
value of a after addition: 5

This means the value changes inside the function (function scope), but outside the function, the value doesn't change.

I know you need more details to understand this. Let's check this diagram:

You get it now. This creates a new variable with a different address (which is not good for memory either!).

This is why we don't see the changes because the variables are different😅.

To solve this problem, we can use a pointer instead of a copy of the value, like this:

func main() {
    a := 5
    fmt.Println("value of a:", a)
    sum(&a)
    fmt.Println("value of a after addition:", a)
}
func sum(x *int) {
    *x += *x
}

Now, instead of the value, we pass the memory address sum(&a). This means the function will work with the same variable and will not create a new one.

 

challenge icon

Challenge

Easy

In the given code, we define a function that swaps two values. Complete the code in order to get the function to work and achieve the result.

Try it yourself

package main

import "fmt"


func swapValues(a, b int) {
	
  a, b = b, a
}

func main() {
	var x, y int = 4,10

	fmt.Println("Before swap:")
	fmt.Println("x =", x)
	fmt.Println("y =", y)

	swapValues(x, y)

	fmt.Println("After swap:")
	fmt.Println("x =", x)
	fmt.Println("y =", y)
}

All lessons in Functions and Pointers in Golang