Go Language Function Value Reference Passing
Reference passing refers to passing the address of the actual parameter to the function when it is called. Any modifications made to the parameter within the function will affect the actual parameter.
Reference passing involves passing pointer parameters into the function. The following is an example of a swap function, swap()
, that uses reference passing:
/* Define the swap function */
func swap(x *int, y *int) {
var temp int
temp = *x /* Keep 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 */
}
Here is how we call the swap()
function using reference passing:
package main
import "fmt"
func main() {
/* Define local variables */
var a int = 100
var b int = 200
fmt.Printf("Before swapping, value of a : %d\n", a)
fmt.Printf("Before swapping, value of b : %d\n", b)
/* Call 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 swapping, value of a : %d\n", a)
fmt.Printf("After swapping, value of b : %d\n", b)
}
func swap(x *int, y *int) {
var temp int
temp = *x /* Save 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 output of the above code is:
Before swapping, value of a : 100
Before swapping, value of b : 200
After swapping, value of a : 200
After swapping, value of b : 100