Go language function reference pass value
Reference passing means that the address of the actual parameter is passed to the function when the function is called, so the modification of the parameter in the function will affect the actual parameter.
The reference passes the pointer parameter to the function, and here is the exchange function swap()
reference was used to pass:
/* Defining Exchange Value Functions*/
func swap(x *int, y *int) {
var temp int
temp = *x /* Maintain the value on the x address */
*x = *y /* Assign y value to x */
*y = temp /* Assign the temp value to y */
}
We call the following by using reference passing swap()
function:
package main
import "fmt"
func main() {
/* Define local variables */
var a int = 100
var b int= 200
fmt.Printf("Value of a before exchange : %d\n", a )
fmt.Printf("Value of b before exchange: %d\n", b )
/* Calling the swap () function
* &A points to the pointer a, and the address of the variable a
* &b Pointer to b, address of b variable
*/
swap(&a, &b)
fmt.Printf("After exchange, the value of a : %d\n", a )
fmt.Printf("After exchange, the value of b : %d\n", b )
}
func swap(x *int, y *int) {
var temp int
temp = *x /* Save values on address x */
*x = *y /* Assign y value to x*/
*y = temp /* Assign the temp value to y*/
}
The result of the above code execution is:
Value of a before exchange: 100
Value of b before exchange: 200
After exchange, the value of a: 200
After exchange, the value of b: 100