Go Function Call By Reference
# Go Function Call by Reference
[Go Functions](#)
Pass by reference means that the address of the actual parameter is passed to the function when calling it. Any modifications made to the parameter inside the function will affect the actual parameter.
Pass by reference involves passing pointer parameters to the function. Here is the swap() function using pass by reference:
/* Define a function to swap values */ func swap(x *int, y *int) { var temp int temp = *x /* Store the value at the address of x */ *x = *y /* Assign the value of y to x */ *y = temp /* Assign the value of temp to y */}
Below, we call the swap() function using pass by reference:
package main import "fmt" func main() { /* Define local variables */ var a int = 100 var b int= 200 fmt.Printf("Before swap, value of a : %dn", a ) fmt.Printf("Before swap, value of b : %dn", b ) /* Call the swap() function * &a points to the pointer of a, the address of variable a * &b points to the pointer of b, the address of variable b */ swap(&a, &b) fmt.Printf("After swap, value of a : %dn", a ) fmt.Printf("After swap, value of b : %dn", b )} func swap(x *int, y *int) { var temp int temp = *x /* Store the value at the address of x */ *x = *y /* Assign the value of y to x */ *y = temp /* Assign the value of temp to y */}
The result of executing the above code is:
Before swap, value of a : 100Before swap, value of b : 200After swap, value of a : 200After swap, value of b : 100
[Go Functions](#)
YouTip