Go 语言函数值传递值
Go 函数
传递是指在调用函数时将实际参数复制一份传递到函数中,这样在函数中如果对参数进行修改,将不会影响到实际参数。
默认情况下,Go 语言使用的是值传递,即在调用过程中不会影响到实际参数。
以下定义了 swap() 函数:
func swap(x, y int) int {
var temp int
temp = x
x = y
y = temp
return temp;
}
接下来,让我们使用值传递来调用 swap() 函数:
package main
import "fmt"
func main() {
var a int = 100
var b int = 200
fmt.Printf("交换前 a 的值为 : %dn", a )
fmt.Printf("交换前 b 的值为 : %dn", b )
swap(a, b)
fmt.Printf("交换后 a 的值 : %dn", a )
fmt.Printf("交换后 b 的值 : %dn", b )
}
func swap(x, y int) int {
var temp int
temp = x
x = y
y = temp
return temp
}
以下代码执行结果为:
交换前 a 的值为 : 100
交换前 b 的值为 : 200
交换后 a 的值 : 100
交换后 b 的值 : 200
Go 函数