Go language function value transfer value
Transfer means that when you call the function to copy the actual parameters passed to a function, so that if the function parameters can be modified, will not affect the actual parameters.
By default, Go language is passed by value, that is, during the call will not affect the actual parameters.
The following definitions of the swap () function:
/* 定义相互交换值的函数 */ func swap(x, y int) int { var temp int temp = x /* 保存 x 的值 */ x = y /* 将 y 值赋给 x */ y = temp /* 将 temp 值赋给 y*/ return temp; }
Next, let us use the value passed to the call swap () function:
package main import "fmt" func main() { /* 定义局部变量 */ var a int = 100 var b int = 200 fmt.Printf("交换前 a 的值为 : %d\n", a ) fmt.Printf("交换前 b 的值为 : %d\n", b ) /* 通过调用函数来交换值 */ swap(a, b) fmt.Printf("交换后 a 的值 : %d\n", a ) fmt.Printf("交换后 b 的值 : %d\n", b ) } /* 定义相互交换值的函数 */ func swap(x, y int) int { var temp int temp = x /* 保存 x 的值 */ x = y /* 将 y 值赋给 x */ y = temp /* 将 temp 值赋给 y*/ return temp; }
The following code execution results:
交换前 a 的值为 : 100 交换前 b 的值为 : 200 交换后 a 的值 : 100 交换后 b 的值 : 200