How to do call by value vs call by reference in go lang.

In this tutorial, you can learn how to call functions in go using call by value and call by reference. As you know go is supporting pointer variable.

Everything is passed by value in Go. When we pass a pointer to a type, a separate copy of that pointer is created. This is different from C, where in the case of pointers, the same pointer is passed to the function.

Call by value:

It means in the go code within a function cannot alter the arguments used to call the function.

func swapbyvalue(int x, int y) int {
   var temp int

   temp = x // save the value of x 
   x = y    // put y into x 
   y = temp // put temp into y 

   return temp;
}



func main() {
   // variables scope is within the main()
   var x int = 100
   var y int = 200

   fmt.Printf("Before swaping, value of x : %d\n", x )
   fmt.Printf("Before swaping, value of y : %d\n", y )

   // call the function with x and y values
   swapbyvalue(x, y)

   fmt.Printf("After swaping, value of x : %d\n", x )
   fmt.Printf("After swaping, value of y : %d\n", y )
}

In the above code snippet, we are passing two-argument x and y and returns the value. Whatever the values we passed here if any changes happen in these variables will not affect the original value. Its scope is within that function.

Call By Reference:

 Inside the function, the memory address is used to access the actual argument used in the call. This means that changes made to the input parameter affect the passed argument. Let us take the example, where we are creating one struct and pass that struct to function and change the value. To call by reference, argument pointers are passed to the functions just like any other value.


type Employee struct {
    name       string
    occupation string
}

func main(){

e := Employee{"Mahesh Ligade", "teacher"}
    fmt.Printf("inside main %v\n", e)

    modify(e)
    fmt.Printf("inside main %v\n", e)
}
func modify(e Employee) {

    e.occupation = "driver"
    fmt.Printf("inside modify %v\n", e)
}

Conclusion:

Call by value is simple but call by reference is a bit different as compared to C language. When we pass a pointer to a type, a separate copy of that pointer is created. Everything in go is called by value only.

Source Code:

https://github.com/maheshwarLigade/spring-boot-examples
$ git clone https://github.com/maheshwarLigade/GoLanguage-tutorials
$ cd GoLanguage-tutorials
$ go run passbyvaluebyref.go