Follow

Follow

How To Do Call By Value Vs Call By Reference In Go Lang.

Maheshwar Ligade's photo
Maheshwar Ligade
ยทApr 26, 2022ยท

3 min read

Play this article

Table of contents

  • Call by Value:
  • Call by Reference:
  • Conclusion:

In Go, there are two ways to pass arguments to a function: call by value and call by reference. In call by value, the value of the argument is copied to a new variable and passed to the function, while in the call by reference, the memory address of the argument is passed to the function. In this article, we will discuss the differences between these two methods with examples.

Call by Value:

When a function is called using call by value, a new copy of the variable is created and passed to the function. The function can modify the value of the copy, but the original value remains unchanged.

Let's take an example to understand call by value:

package main

import "fmt"

func swap(x, y int) {
    var temp int
    temp = x
    x = y
    y = temp
}

func main() {
    a, b := 5, 10
    fmt.Println("Before swapping, a=", a, "b=", b)
    swap(a, b)
    fmt.Println("After swapping, a=", a, "b=", b)
}

Output:

Before swapping, a= 5 b= 10
After swapping, a= 5 b= 10

In the above example, the swap function takes two arguments x and y. Inside the function, a temporary variable is used to swap the values of x and y. However, when we call the swap function with a and b, the values of a and b remain unchanged because the function is called using call by value.

Call by Reference:

When a function is called using call by reference, a pointer to the variable is passed to the function. The function can then access and modify the value of the variable using the pointer.

Let's take an example to understand call by reference:

package main

import "fmt"

func swap(x, y *int) {
    var temp int
    temp = *x
    *x = *y
    *y = temp
}

func main() {
    a, b := 5, 10
    fmt.Println("Before swapping, a=", a, "b=", b)
    swap(&a, &b)
    fmt.Println("After swapping, a=", a, "b=", b)
}

Output:

Before swapping, a= 5 b= 10
After swapping, a= 10 b= 5

In the above example, the swap function takes two pointers x and y. Inside the function, a temporary variable is used to swap the values of *x and *y. When we call the swap function with the address of a and b, the values of a and b are swapped because the function is called using call by reference.

Conclusion:

In Go, call by value and call by reference are two ways to pass arguments to a function. Call by value creates a new copy of the variable and passes it to the function, while call by reference passes a pointer to the variable to the function. It is important to choose the appropriate method based on the requirements of the program.

Did you find this article valuable?

Support techwasti by becoming a sponsor. Any amount is appreciated!

See recent sponsors |ย Learn more about Hashnode Sponsors
ย 
Share this