Go Function Pass-by-Reference
Pass-by-reference means passing the address of the actual argument to the function when calling it, so any modifications to the parameter inside the function will affect the actual argument.
Pass-by-reference passes a pointer parameter into the function; the following swap() function uses pass-by-reference:
/* 定义交换值函数*/
func swap(x *int, y *int) {
var temp int
temp = *x /* 保持 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("交换前,a 的值 : %d\n", a )
fmt.Printf("交换前,b 的值 : %d\n", b )
/* Call swap() function
* &a points to a pointer, the address of variable a
* &b points to the b pointer, the address of variable b
*/
swap(&a, &b)
fmt.Printf("交换后,a 的值 : %d\n", a )
fmt.Printf("交换后,b 的值 : %d\n", b )
}
func swap(x *int, y *int) {
var temp int
temp = *x /* 保存 x 地址上的值 */
*x = *y /* assign the value of y to x */
*y = temp /* Assign the value of temp to y */
}
The execution result of the code above is:
交换前,a 的值 : 100
交换前,b 的值 : 200
交换后,a 的值 : 200
交换后,b 的值 : 100
Go Functions